简体   繁体   English

Python中的Selenium:选择具有给定链接文本的第二个元素

[英]Selenium in Python: Select the second element with given link text

I am trying to click all of the links on a web page that contain the link text "View all hits in this text." 我正在尝试单击网页上包含链接文本“查看此文本中的所有匹配”的所有链接。 Here's what some of the html on the web page looks like: 这是网页上的一些html的样子:

<a href="/searchCom.do?offset=24981670&entry=4&entries=112&area=Poetry&forward=textsCom&queryId=../session/1380145118_2069"><b>View all hits in this text</b>
<br>
</a>

[...]

<a href="/searchCom.do?offset=25280103&entry=5&entries=112&area=Poetry&forward=textsCom&queryId=../session/1380145118_2069"><b>View all hits in this text</b>
<br>
</a>

If there were only one such link on the page, I know I could click it using something like: 如果页面上只有一个这样的链接,我知道我可以使用以下内容点击它:

driver.find_element_by_link_text('View all hits in this text').click()

Unfortunately, this method only ever identifies and clicks the first link on the web page with the link text "View all hits in this text." 不幸的是,此方法只识别并点击网页上的第一个链接,其中包含链接文本“查看此文本中的所有匹配”。 I therefore wanted to ask: is there a method I can use to click the second (or nth) link with link text "View all hits in this text" on this page? 因此,我想问:是否有一种方法可以用来点击第二个(或第n个)链接,链接文本“查看此文本中的所有匹配”? I have a feeling I may need to use xpath, but I haven't quite figured out how I should go about implementing xpath in my script. 我有一种感觉,我可能需要使用xpath,但我还没有弄清楚我应该如何在我的脚本中实现xpath。 I would be grateful for any advice others can lend. 我会很感激任何其他人可以借出的建议。

There is find_elements_by_link_text() ( docs ): find_elements_by_link_text()docs ):

links = driver.find_elements_by_link_text('View all hits in this text')
for link in links:
    link.click()

Also, you can use xpath to get all links with a specified text: 此外,您可以使用xpath获取具有指定文本的所有链接:

links = driver.find_elements_by_xpath("//a[text() = 'View all hits in this text']")
for link in links:
   link.click()

Hope that helps. 希望有所帮助。

试试以下代码:

driver.find_elements_by_link_text('linktext')[1].click()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM