In Selenium using Java, you can find an element by its text using the XPath method.
Here is an example of how to find an element with the text "Text" using XPath:
WebElement element = driver.findElement(By.xpath("//*[text()='Text']"));
We can also prefer the contains method using XPath to fetch elements based on text.
//*[ contains (text(), 'Text' ) ]
Let us try to fetch the ask doubt text of our programsbuzz site.
WebDriverManager.chromedriver().setup(); ChromeDriver driver = new ChromeDriver(); driver.get("https://www.programsbuzz.com/"); driver.manage().window().maximize(); Thread.sleep(3000); driver.findElement(By.xpath("(//a[text()='Ask Doubt'])")).click();
- have provided it with the index as it was present on the second index.
- After some animation wait time, it will click on the ask doubt button on the second index.
(//*[ contains (text(), 'Ask Doubt' ) ])
- The same thing can also be done using contains too.