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.
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.
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 1')]"));
We can also use a single period/dot, ".
", instead of the text()
function in following way:
WebElement cell = driver.findElement(By.xpath("//td[contains(.,'Item 1')]"));
Here, we are using the contains...