
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Element Containing Specific Text in Selenium WebDriver
We can find an element with a specific text visible on the screen in Selenium. This is achieved with the xpath locator. The xpath locator contains some in-built functions that help to create customized xpath.
Let us consider a portion of the web page as given below −
text() − It is a built in function to identify an element based on the text displayed on the screen. For example, if we want to identify Library from the above webpage, the customized xpath with text() should be −
Syntax
//*[text()='Library']
contains() − It is a built in function to identify an element based on the partial text match. For example, if we want to identify GATE Exams from the above webpage, the customized xpath with contains() should be
Syntax
//*[contains(text(),'GATE')]
Example
Code Implementation .
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class TextMatch{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element with text() WebElement l=driver.findElement(By.xpath("//*[text()='Library']")); // identify element with contains() WebElement m=driver.findElement(By.xpath("//*[contains(text(),'GATE')]")); System.out.println("Element with text(): " + l.getText()); System.out.println("Element with contains(): " + m.getText()); driver.quit(); } }
Output
Advertisements