duhaime
duhaime

Reputation: 27612

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:

<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? 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. I would be grateful for any advice others can lend.

Upvotes: 6

Views: 5761

Answers (2)

Vani
Vani

Reputation: 51

Try this below code:

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

Upvotes: 2

alecxe
alecxe

Reputation: 474041

There is 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:

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

Hope that helps.

Upvotes: 6

Related Questions