8

我正在开发一个系统,该系统具有我正在使用 Selenium 测试的基于 Web 的前端。在一个页面上,向下滚动时会动态加载内容(也许您从 Facebook 的好友列表中知道),因为这是要求之一。

通过 Javascript 使用 Selenium Webdriver(我使用 Chrome)向下滚动应该没问题。但是动态添加的内容存在问题。如何让 Webdriver 找到这些元素?

我尝试了以下内容向下滚动,直到不再加载内容:

int oldSize = 0;
int newSize = 0;
do {
  driver.executeScript("window.scrollTo(0,document.body.scrollHeight)");
  newSize = driver.findElementsBy(By.cssSelector("selector").size();
} while(newSize > oldSize);

但是,尽管页面第一次向下滚动并且现在正确加载了一些内容,但驱动程序的 findElementsBy(By) 函数将无法找到它们。

有人遇到过这个问题吗??如果有人可以帮助我找到解决方案,我将非常高兴!

问候, 本杰明

4

3 回答 3

4

我建议将 WebDriverWait 与 ExpectedConditons 一起使用。

//scroll down with Javascript first
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("selector")));
//interact with your element
element.click()

看看 Selenium 官方页面提供的指导:http: //seleniumhq.org/docs/04_webdriver_advanced.html

于 2012-10-02T19:10:58.457 回答
1

特别尝试使用流利的等待。主要特点是:

一个 Wait 接口的实现,可以动态配置它的超时和轮询间隔。每个 FluentWait 实例定义等待条件的最长时间,以及检查条件的频率。此外,用户可以将等待配置为在等待时忽略特定类型的异常,例如在页面上搜索元素时的 NoSuchElementExceptions。

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;              }     ;

所描述的方法返回您可以操作的 Web 元素。所以方法如下:1)你需要找到你希望在滚动后呈现的元素的选择器,例如

String cssSelector = "blablabla"

2) 使用 js 向下滚动 3)

WebElement neededElement  = fluentWait(cssSelector);
neededElement.click();
//neededElement.getText().trim();

您可以在此处获取有关流利等待的更多信息

于 2012-10-04T14:06:52.873 回答
0

我认为问题在于等待动态内容完成加载。尝试在 findElementsBy 之前等待 3 秒?在 C# 中,代码为 Thread.Sleep(3000);

于 2012-10-02T17:14:14.953 回答