Search code examples
seleniumselenium-webdrivercodeception

Is there a way to click plain text in Codeception acceptance tests without using XPath?


Using Codeception acceptance test (with WebDriver), I would like to know if there is a way to click an element that contains a specific text, without that element being a link or a button. I know it can be done using XPath, but I'm looking for a more readable solution that uses CSS-selectors for example.


Solution

  • Without specific examples, probably the best you could do is to look for a group of elements using a CSS selector then loop through that collection looking for contained text. Here's a contrived example where I'm looking for a TD that contains the text "Click here".

    List<WebElement> cells = driver.findElements(By.cssSelector("td.someclass"));
    for (WebElement cell : cells)
    {
        if (cell.getText().contains("Click here"))
        {
            cell.click();
            break; // found it, don't need to keep looping
        }
    }
    

    If you want your search to look for the text, then XPath is your only option.