Locating elements using text

When testing web applications, you will also encounter situations where developers don't assign any attributes to the elements and it becomes difficult to locate elements.

Using the CSS selectors or XPath, we can find elements based on their text contents. In this recipe, we will explore methods to find elements using text values.

How to do it...

To find elements using their text contents, CSS selectors and XPath provide methods to find text within the elements. If an element contains specific text, this will return the element in the test.

Using XPath's text function

XPath provides the text() function, which can be used to see if an element contains the specified text in the following way:

WebElement cell = driver.findElement(By.xpath("//td[contains(text(),'Item ...

Get Selenium Testing Tools Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.