Select element by containing text without XPath in Selenium



  • There is a great discussion on what makes a good Selenium locator here.

    It seems many testers prefer CSS to XPath for locators, for various reasons. And that goes for me, too.

    But, it is often very convenient to use XPath's //*[contains(.,'some text')], especially when selecting dynamic elements from a table. For example, you wish to enter a new element to a table and click a button next to it. You can make a generic locator of type "//*[contains(.,"'+new_element_name+'")]/button".

    How can you do that without using XPath?



  • When there really is no better way, you can always find all elements and search for the text

    driver.findElements(By.cssSelector("button")).stream()
          .filter(e -> e.getText().contains("search text"))
          .findFirst();
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2