Select Element By Text in Selenium

后端 未结 4 885
眼角桃花
眼角桃花 2021-01-23 02:17

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:

相关标签:
4条回答
  • 2021-01-23 02:45

    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.

    0 讨论(0)
  • 2021-01-23 02:50

    Try to use methods in XPath.

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

    Hope this will work!

    0 讨论(0)
  • 2021-01-23 03:01

    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>

    0 讨论(0)
  • 2021-01-23 03:07

    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;
                }
            }
    
    0 讨论(0)
提交回复
热议问题