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 following web document.

index.html

<html>
 <body>
  <p>Paragraph 1</p>
  <div name="xyz">
      <p>>Article 1</p>
      <a href="/article-1/">Read More</a>
  </div>
  <div name="xyz">
    <p>>Article 2</p>
    <a href="/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.webdriver.chrome.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By

service = Service(executable_path="/usr/local/bin/chromedriver")
#initialize web driver
with webdriver.Chrome(service=service) as driver:
    #navigate to the url
    driver.get('http://127.0.0.1:5500/localwebsite/index.html')
    #find elements by link text
    elements = driver.find_elements(By.LINK_TEXT, 'Read More')
    for element in elements:
        print(element.get_attribute("outerHTML"))
Run

Output

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

Summary

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