Selenium:在动态加载网页中滚动到页面末尾 [英] Selenium: Scroll to end of page in dynamically loading webpage

查看:314
本文介绍了Selenium:在动态加载网页中滚动到页面末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a webpage that keeps loading new items when scrolling down the page until every item is loaded.

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

I'm working with Selenium in Java, and need to scroll down to the bottom of the page in order to load everything.

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

I have tried several different options, like scrolling to an element of the bottom of the page:

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

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

This only scrolls down once though, and then the webpage keeps loading.

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

I also tried this approach, which also only scrolls down once, because it only takes the browser height into consideration.

我们非常感谢您的帮助.

Any help is highly appreciated.

推荐答案

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

I will provide you code in Python for this. I think it's easy to translate to 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

希望对您有帮助!

这篇关于Selenium:在动态加载网页中滚动到页面末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆