Selenium XPath Contains

Profile picture for user arilio666

In Selenium, you can use the contains function in an XPath expression to match elements with a specific text within its attribute value.

For example:

//*[contains(text(),'Search')]
  • This expression will match all elements with a text() value that contains the word "Search." 
  • The * wildcard can be replaced with the desired HTML tag name to search for elements with specific tag types.
<html>
<body>
<div id="electronics"><br><br><br><br><br><br><br><br><br><br><br>
<button type="button">Iphone</button><br><br>
<button type="button" >Airpods</button><br><br>
<button type="button">Mac</button><br><br>
</div>
</body>
</html>
  • Now consider this DOM, which has texts of all electronics. Suppose we want to fetch mac. We can write XPath contains as.
//button[contains(text(),'Mac')]
  • There is no need to supply full text when it only contains partial texts that are also supported.
  • We can also identify attributes using contains.
div[contains(@value.’not’)]
  • The @ is used to access the attributes.
  • Now let us search Selenium in the programsbuzz site, isolate a topic, and click. For example, let us take a topic with a name that contains 'Jacob' and click it.
  • Here, it isolated Jacob and fetched the topic using XPath contains.
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("https://www.programsbuzz.com/search/node?keys=selenium");
        driver.manage().window().maximize();
        driver.findElement(By.xpath("//a[contains(text(),'Jacob')]")).click();
  • This is how we can use xpath contains in Selenium effectively.