1

WebDriver get() 和 isDisplayed() 方法没有按我的预期工作。

至于文档

这是使用 HTTP GET 操作完成的,该方法将阻塞直到加载完成

正如在 Selenium 中等待页面加载这样的其他问题中提到的,get 方法应该等待页面加载。

但是在运行 get() 之后,来自 RenderedWebElement 的 isDisplayed() 方法并不总是在某些元素上返回 true。

可能的原因是什么?

我想详细说明在 webdrivers 上下文中加载和显示之间的区别。

4

2 回答 2

1

在最新的 UI 框架/API 中,您可以隐藏页面上的元素。

例如。考虑一个有 5 个元素的页面。当页面加载时,页面上只会显示 3 个元素,另外 2 个将被隐藏,并且在采取一些操作时,其他 2 个元素将被显示。

您可以在以下链接中的演示部分查看示例:

显示元素链接:http ://api.jquery.com/show/

隐藏元素链接:http ://api.jquery.com/hide/

当您使用 webDriver get() 方法时,webdriver 将等待页面加载,即等待页面的所有 html 内容加载到浏览器上。这并不意味着所有元素都是可见的。

当您使用 isDisplayed() webdriver 检查所述元素是否显示在页面上。如果您知道在运行测试用例时该元素可能隐藏在页面上,那么这是验证该元素是否显示的好方法。否则,您的测试脚本将失败并显示错误“未显示元素以执行操作”

希望这可以帮助。

于 2012-09-25T08:59:05.083 回答
0

isDisplayed() 在我看来不是很好的方法。从等待中获得一些想法:显式和隐式等待机制:

Explicit wait
WebDriverWait.until(condition-that-finds-the-element)

Implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);


Explicit Waits:

WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(new ExpectedCondition<WebElement>(){
    @Override
    public WebElement apply(WebDriver d) {
        return d.findElement(By.id("myDynamicElement"));
    }});

Implicit Waits:

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));

The example what you have given both do exact same thing.. 
In Explicit wait, WebDriver evaluates the condition every 500 
milliseconds by default ..if it is true, it comes out of loop 

Where as in ImplicitWait WebDriver polls the DOM every 500 
milliseconds to see if element is present.. 

Difference is 
1. Obvious - Implicit wait time is applied to all elements in your 
script but Explicit only for particular element 
2. In Explicit you can configure, how frequently (instead of 500 
millisecond) you want to check condition. 
3. In Explicit you can also configure to ignore other exceptions than 
"NoSuchElement" till timeout.. 

你可以在这里获得更多信息

我还使用流利的等待机制来等待元素在页面上呈现。实际上,您将 css 选择器或 xpath 传递给函数并简单地获取 web 元素。

public WebElement fluentWait(final By locator){
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class);

        WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                        return driver.findElement(locator);
                }
                }
);
                           return  foo;              }     ;

流利的等待说明

希望这现在清楚了)

于 2012-09-21T15:18:17.330 回答