Selenium 2.0 Web Driver: implementation of isTextP

2019-06-19 01:54发布

问题:

I'm looking for a working implementation of this. The best I've come up with is:

    public boolean isTextPresent(String string) {

        for (WebElement e : drv.findElements(By.cssSelector("*"))) {

            if (e.isDisplayed() && e.getText().contains(string)) {
                return true;
            }

        }
        return false;
    }

回答1:

A faster way to do it would be something like this:

public boolean isTextPresent(string str)
{
    IWebElement bodyElement = driver.FindElement(By.TagName("body"));
    return bodyElement.Text.contains(str);
}

It's in C# but it's the same concept. Getting the text of the body tag automatically returns the text of all the nested elements. The only thing I'm not sure about is if hidden elements are included or not.



回答2:

The following code using Java in WebDriver should work fine as isTextPresent:

assertTrue(driver.getPageSource().contains("Welcome Ripon"));
assertTrue(driver.findElement(By.id("widget_205_after_login")).getText().matches("^[\\s\\S]*Welcome ripon[\\s\\S]*$"));