Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

selenium
python
link text
partial link text

How to locate elements by link and partial link texts in Selenium

Gutha Vamsi Krishna

Overview

Selenium is an open-source web-based automation tool. In this answer, we learn how to find elements by link text or partial link text using the Selenium web driver in Python.

The link text is the text that we get from the anchor tag in HTML.

Syntax

driver.find_element(By.LINK_TEXT, 'provide complete text of a link')
driver.find_element(By.PARTIAL_LINK_TEXT, 'provide partial text of a link')

Example

Let's take a look at an example of this.

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

#Specifying where the Chrome driver is present in our PC
PATH=r"C:\Users\educative\Documents\chromedriver\chromedriver.exe"

#Getting the instance of the web driver
driver = webdriver.Chrome(PATH)

#Providing the website URL
driver.get("https://www.educative.io/")

#Using LINK_TEXT
print(driver.find_element(By.LINK_TEXT, 'compendiumdev').get_attribute("href"))

#Using PARTIAL_LINK_TEXT
print(driver.find_element(By.PARTIAL_LINK_TEXT, 'dev').get_attribute("href"))
Locating elements by link text and partial link text using Selenium in Python

Explanation

  • Line 12: We open the URL using the driver.get() method.
  • Line 15: We find the element using LINK_TEXT and get its URL using the get_attribute() method. Here, we provide the full text of the compendiumdev link text.
  • Line 18: We find the element using PARTIAL_LINK_TEXT and get its URL using the get_attribute() method. Here, we only provide the partial text of the dev link text.

Note: Both elements print the same URL because they refer to the same element.

RELATED TAGS

selenium
python
link text
partial link text
RELATED COURSES

View all Courses

Keep Exploring