How to find Elements by Link Text using Selenium?


Find Elements by Link Text

To find the link elements (hyperlinks) by the value (link text) inside the link, using Selenium in Python, call find_elements() method, pass By.LINK_TEXT as the first argument, and the link text as the second argument.

find_elements(By.LINK_TEXT, "link_text_value")

find_elements() method returns all the HTML Elements, that match the given link text, as a list.

If there are no elements by given link text, find_elements() function returns an empty list.

Example

Consider the HTML document at the URL /tmp/selenium/index-56.html, with the following HTML content.

HTML Webpage

<html>
 <body>
  <p>Paragraph 1</p>
  <div name="xyz">
    <p>Article 1</p>
    <a href="/tmp/article-1/">Read More</a>
  </div>
  <div name="xyz">
    <p>Article 2</p>
    <a href="/tmp/article-2/">Read More</a>
</div>
 </body>
</html>

In the following Python program, we will find all the HTML elements that have link text 'Read More', and print those elements to the console.

Python Program (Selenium)

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# Navigate to the url
driver.get('/tmp/selenium/index-56.html')

# Find elements by Link Text
my_elements = driver.find_elements(By.LINK_TEXT, 'Read More')
for element in my_elements:
    print(element.get_attribute("outerHTML"))

# Close the driver
driver.quit()

Output

<a href="/tmp/article-1/">Read More</a>
<a href="/tmp/article-2/">Read More</a>

Summary

In this Python Selenium tutorial, we learned how to find all the elements that have given link text, in the webpage, using Selenium.