java – Selenium WebDriver getText

I have a < div name = "mydiv" > 0 < / div >

I try to write a test with 0 text in mydiv Use webdriver, which is:

String text =  webDriver.findElement(By.xpath("//div[@name='myDiv']")).getText();

But I ended up with an empty string Shouldn't I use gettext () to get the contents of div?

Solution

I have the same problem; A little digging reminds me of this:

https://groups.google.com/forum/# ! msg/webdriver/fRb_ 1QOr3wg/wzUsW3Ll6bgJ

When you try to call webelement #gettext() on an element whose CSS property "display" is set to "None", the htmlunitdriver (obviously Firefox driver) will return an empty string

This is my solution:

public void assertContainsText(final By by,final String value) { 
    browser.waitTillElementPresent(by);
        Boolean result = new webdriverwait(getWebDriver(),Browser.DEFAULT_WAIT_TIMEOUT_SECONDS).until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver arg0) {
                WebElement elem = arg0.findElement(by);
                String text = "";
                if (elem.isDisplayed()) {
                    text = elem.getText();
                } else {
                  //have to use JavaScript because HtmlUnit will return empty string for a hidden element's text
                    text = (String) executeScript("return arguments[0].innerHTML",elem);
                    text = text.replace("<BR></BR>","\n"); //scary
                }
                return text.contains(value);
            }
        });
        Assert.assertTrue(by.toString() + " contains value ["+value+"]",result);
}

Yes, it's as ugly as sin Note text Replace ("< br > < / BR >") – this is because HTML tags are not escaped when the original data is pulled out If you call #gettext () on an element, the webdriver will 'unescape' well

I now ask our IT staff to install X - Windows on our CI server so that we can run Firefox driver All we get from htmlunitdriver is trouble, and the startup speed is very slow

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>