How to find Elements by Partial Link Text using Selenium?

Find Elements by Partial Link Text

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

find_elements(By.PARTIAL_LINK_TEXT, "partial_link_text_value")

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

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

For an example to link text, in the following code snippet, About can be the partial link text, or 'article', or 'this article' could be partial link text.

<a href="/about/">About this article</a>

Example

Consider the following html 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>
  <div>
    <p>About</p>
    <a href="/about/">Read about our company</a>
  </div>
 </body>
</html>

In the following Python program, we find all the HTML link elements with the partial link text 'More'.

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 partial link text
    elements = driver.find_elements(By.PARTIAL_LINK_TEXT, 'More')
    for element in elements:
        print(element.get_attribute("outerHTML"))

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 a given partial link text, in the webpage, using Selenium.