Selenium:滚动到页面末尾,动态加载网页

Joh*_*ols 8 javascript java selenium

我有一个网页,在向下滚动页面时不断加载新项目,直到每个项目都加载完毕.

我正在使用Java中的Selenium,需要向下滚动到页面底部才能加载所有内容.

我尝试了几种不同的选项,比如滚动到页面底部的元素:

WebElement copyrightAtEndOfPage = webDriver.findElement(By.xpath("//a[@href='/utils/copyright.html']"));
((JavascriptExecutor) webDriver).executeScript("arguments[0].scrollIntoView();", copyrightAtEndOfPage);
Run Code Online (Sandbox Code Playgroud)

这只会向下滚动一次,然后网页会继续加载.

我也尝试过这种方法,它也只向下滚动一次,因为它只考虑浏览器高度.

任何帮助都非常感谢.

Rat*_*nov 13

我将为您提供Python代码.我认为翻译成Java很容易:

def scroll_down(self):
    """A method for scrolling the page."""

    # Get scroll height.
    last_height = self.driver.execute_script("return document.body.scrollHeight")

    while True:

        # Scroll down to the bottom.
        self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # Wait to load the page.
        time.sleep(2)

        # Calculate new scroll height and compare with last scroll height.
        new_height = self.driver.execute_script("return document.body.scrollHeight")

        if new_height == last_height:

            break

        last_height = new_height
Run Code Online (Sandbox Code Playgroud)

希望它能帮到你!


Joh*_*ols 6

感谢Ratmir Asanov(请参阅上面的批准答案),我将Python代码转换为Java,以使其易于实现。

try {
    long lastHeight = (long) ((JavascriptExecutor) webDriver).executeScript("return document.body.scrollHeight");

    while (true) {
        ((JavascriptExecutor) webDriver).executeScript("window.scrollTo(0, document.body.scrollHeight);");
        Thread.sleep(2000);

        long newHeight = (long) ((JavascriptExecutor) webDriver).executeScript("return document.body.scrollHeight");
        if (newHeight == lastHeight) {
            break;
        }
        lastHeight = newHeight;
    }
} catch (InterruptedException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)