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="/tmp/article-1/">Read More</a>
  </div>
  <div name="xyz">
    <p>>Article 2</p>
    <a href="/tmp/article-2/">Read More</a>
  </div>
  <div>
    <p>About</p>
    <a href="/tmp/about/">Read about our company</a>
  </div>
 </body>
</html>
Copy

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

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('https://pythonexamples.org/tmp/selenium/index-57.html')

# Find elements whose Partial Link Text = "More"
my_elements = driver.find_elements(By.PARTIAL_LINK_TEXT, '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 a given partial link text, in the webpage, using Selenium.

Related Tutorials

Quiz on Selenium

Q1. What is a web driver in Selenium Python?

Not answered

Q2. Which of the following is not a popular web driver used in Selenium Python?

Not answered

Q3. What is the method used to find web elements in Selenium Python?

Not answered

Q4. What is the method used to switch to a different frame in Selenium Python?

Not answered

Q5. What is the method used to take a screenshot in Selenium Python?

Not answered
Code copied to clipboard successfully 👍