How do I find an element that contains specific text in Selenium WebDriver (Python)?

SeleniumAutomation TestingTesting Tools

We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element.

The function text() in xpath is used to locate a webelement depending on the text visible on the page. Another function contains() in xpath is used to locate a webelement with the sub-text of actual text visible on the page.

Let us try to identify the element having the specific text - Privacy Policy.

Syntax

l = driver.find_element_by_xpath("//a[text()='Privacy Policy']")
m = driver.find_element_by_xpath("//a[contains(text(), 'Privacy')]")

Example

from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element with text() xpath
l = driver.find_element_by_xpath("//a[text()='Privacy Policy']")
#identify element with contains xpath
m = driver.find_element_by_xpath("//a[contains(text(), 'Privacy')]")

#get element text

print('Text obtained with text(): ' + l.text)

print('Text obtained with contains(): ' + m.text)

#close browser

driver.quit()

Output

raja
Published on 06-Apr-2021 11:34:10
Advertisements