小编典典

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

selenium

我有一个网页,当向下滚动页面直到每个项目都被加载时,它会不断加载新项目。

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

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

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

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

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

非常感谢您的帮助。


阅读 427

收藏
2020-06-26

共1个答案

小编典典

我将为此提供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

希望对您有帮助!

2020-06-26