Locating Elements by Text in Selenium WebDriver

Locating Elements by Text in Selenium WebDriver

16 July 2024 Stephan Petzl Leave a comment QA

When working with Selenium WebDriver, there are various strategies to identify elements on a web page. One common requirement is locating elements based on the text they contain. While WebDriver provides straightforward methods for finding links by their text, such as find_element_by_link_text and find_element_by_partial_link_text, it is also possible to locate other types of elements (e.g., li, div, span) by their text content.

Using XPath for Text-Based Element Location

Selenium WebDriver supports the use of XPath to locate elements based on the text they contain. This method is highly flexible and can be used across different types of elements. Here is an example of how you can use XPath to locate a div that contains a specific string:

//div[contains(.,'Hello Justin')]

The above XPath expression searches for any div element that contains the text “Hello Justin”. This approach can be adapted to locate other elements by changing the tag name and the text string.

Cross-Browser Considerations

While XPath is a powerful tool, it is important to note that browser compatibility issues may arise. Some browsers might handle XPath differently, leading to inconsistent behavior across different environments. One practical solution to mitigate this issue is to first locate elements by their tag name and then iterate through the list to find the specific text.

Practical Example

Suppose you want to find a span element that contains the text “Sample Text”. Here is how you can implement this in Selenium WebDriver using Python:


from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://example.com")

# Locate the span element by text
element = driver.find_element_by_xpath("//span[contains(.,'Sample Text')]")
print(element.text)

driver.quit()
    

In this example, the find_element_by_xpath method is used to locate a span element containing “Sample Text”. This method is not only effective but also easy to understand and implement.

Enhancing Test Automation with Repeato

Automating tests for mobile applications can be challenging, especially when dealing with complex user interactions and diverse environments. This is where Repeato, a no-code test automation tool for iOS and Android, can be highly beneficial. Repeato leverages computer vision and AI to create, run, and maintain automated tests efficiently. Its intuitive setup and ease of use make it an excellent choice for quality assurance teams looking to streamline their testing processes.

For more information on how to get started with Repeato and enhance your mobile testing strategy, visit our documentation page.

Like this article? there’s more where that came from!