Selenium WebDriver getText

后端 未结 8 2095
广开言路
广开言路 2021-01-06 21:07

I have a

0
.

I try to write a test that myDiv has 0 text in it. With WebDriver it is:

<
8条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 21:37

    I had the same problem; a little digging brought me to this:

    https://groups.google.com/forum/#!msg/webdriver/fRb_1QOr3wg/wzUsW3Ll6bgJ

    HTMLUnitDriver (and apparently FirefoxDriver) will return empty strings when you try to call WebElement#getText() on elements whose CSS property 'display' is set to 'none'.

    Here 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() {
                @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("

    ", "\n"); //scary } return text.contains(value); } }); Assert.assertTrue(by.toString() + " contains value ["+value+"]", result); }

    Yes, it's ugly as sin. And note the text.replace("

    ") - this is because HTML tags aren't escaped when you pull out the raw data. The WebDriver will nicely 'unescape' this if you call #getText() on the element.

    I've now put in a request to our IT guys to install X-Windows on our CI servers so we can run the FirefoxDriver. We've had nothing but trouble from the HTMLUnitDriver, and it's incredibly slow to boot.

提交回复
热议问题