How can I write an XPath expression by using the “contain text”?

37    Asked by CrownyHasegawa in QA Testing , Asked on Apr 9, 2024

 I am currently engaged in a particular task that is related to automated testing of a web-based application by using the selenium WebDriver in Java programming language. In one of my test scenarios, I need to locate an element on the webpage that contains a specific test string within the text content. How can I write an XPath expression by using the ‘contain text’ keyword to find and interact with this element? 

Answered by Connor Peake

 In the context of selenium, you can use the “contains text” keyword in Xpath within the selenium’s WebDriver with Java programming language to locate an element that contains a specific text string within its text content. Here is an example of how you can write the XPath expression and then use it in your particular selenium text script:-


Import org.openqa.selenium.By;
Import org.openqa.selenium.WebDriver;
Import org.openqa.selenium.WebElement;
Import org.openqa.selenium.chrome.ChromeDriver;
Public class ContainsTextExample {
    Public static void main(String[] args) {
        // Set the path to the ChromeDriver executable
        System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
        // Initialize the ChromeDriver instance
        WebDriver driver = new ChromeDriver();
        // Navigate to the webpage
        Driver.get(https://www.example.com);
        // Find the element using XPath with ‘contains text’ keyword
        // Replace “textToFind” with the specific text string you want to search for
        String textToFind = “Example Text”;
        WebElement element = driver.findElement(By.xpath(“//*[contains(text(), ‘” + textToFind + “’)]”));
        // Perform actions on the found element (e.g., click, send keys)
        Element.click();
        // Close the WebDriver instance
        Driver.quit();
    }
}

This above approach would allow you to locate the element dynamically based on the content which are your using the “contains text” keyword in the Xpath with selenium’s WebDriver in the Java programming language.



Your Answer

Interviews

Parent Categories