3

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 4

5

There is a linkText method:

driver.findElement(By.linkText("Some Text"))

You also have partialLinkText:

driver.findElement(By.partialLinkText("Partial Text"))

For examples, see how-to-locate-element-by-link-text-and-partial-link-text-locator

Edit: As @Cajova_Houba mentioned that it works only for anchor elements <a>

Sign up to request clarification or add additional context in comments.

2 Comments

listed methods will select elements that has a tag, methods won't work for other elements
@NodirNasirov you are right! See the last line in the answer... This is a good question there for I have upvoted... I think you should suggest this feature to selenium via GitHub... As for my answer some stack overflow users may find it helpful... Henc my answer...
1

Try to use methods in XPath.

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

Hope this will work!

1 Comment

If you read the question, I said that I am well aware of xpath, and project has limitations, using xpath is prohibited.
0

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;
            }
        }

1 Comment

I confess I have never seen a page with 1000s of buttons but I will take your word they exist. I don't know how long it takes findElements to find all of the elements on the page but I think the java loop would handle several thousand items without a noticeable delay.
-1

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.

1 Comment

I know about linkText and partialLinkText, those methods are for links only, not for elements with other tags

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.