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.
click();//If there are only two such element, here 1 is index of 2nd element in list returned. Option two works!
We can get text from multiple elements with the same class in Selenium webdriver. We have to use find_elements_by_xpath(), find_elements_by_class_name() or find_elements_by_css_selector() method which returns a list of all matching elements.
A linkText is used to identify the hyperlinks on a web page. It can be determined with the help of an anchor tag (<a>). In order to create the hyperlinks on a web page, you can use anchor tags followed by the linkText.
We can click on a link using Selenium webdriver in Python. A link is represented by the anchor tag. A link can be identified with the help of the locators like - link text and partial link text. We can use the link text attribute for an element for its identification and utilize the method find_element_by_link_text.
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.
Try this below code:
driver.find_elements_by_link_text('linktext')[1].click()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With