Select Element By Text in Selenium

Viewed 1726

This may sound so simple but why there is no method to find element by its inner text without using xpath? for instance there is an element:

<button>Some Text</button>

and Selenium does not provide any methods to select it by inner text. Something like:

driver.findElement(By.innerText("Some Text");

What is the the other way to find element by inner text? I am well aware of xpath, but I can not use it because of restrictions of the project.

4 Answers

Try to use methods in XPath.

driver.findElement(By.xpath("//button[text()='Some Text']"));

Hope this will work!

I think this works in java.

        WebElement chosenElement;
        List<WebElement> elements = driver.findElements(By.tagName("button"));
        for(WebElement element:elements){
            if(element.getText().equals("Some Text")){
                chosenElement = element;
                break;
            }
        }

It doesn't seem to be possible for every element, according to Selenium documentation. You can try to use

By.linkText("link text")

or

By.partialLinkText("partial link text")

But that works for anchor elements (<a>) only.

Related