- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I find an element that contains specific text in Selenium WebDriver (Python)?
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
Advertisements