JavascriptExecutor不执行滚动操作

时间:2019-04-06 18:24:06

标签: javascript java selenium

我正在自动测试youtube视频;以这个为例-https://www.youtube.com/watch?v=AjWfY7SnMBI。 我想向下滚动页面以检查是否加载了评论。但是不执行Javascript,也不进行滚动。测试通过,因为没有错误消息。可能是什么原因造成的?

我尝试了以下操作:

js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
js.executeScript("window.scrollTo(0, 2500);");

都不行。

public void scrolledCommentCount() throws InterruptedException{
    JavascriptExecutor js = (JavascriptExecutor)driver;
    js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
    Thread.sleep(9000);
    System.out.print("Scrolled");

3 个答案:

答案 0 :(得分:1)

YouTube似乎没有为document.body.scrollHeight设置值(即为零),因此这可能就是您的第一种方法不起作用的原因。有多个变量用于定义文档高度,并非所有站点都具有所有值。网站here建议使用以下方法找到身高:

window.myScrollHeight = Math.max(
  document.body.scrollHeight, document.documentElement.scrollHeight,
  document.body.offsetHeight, document.documentElement.offsetHeight,
  document.body.clientHeight, document.documentElement.clientHeight
);

将该命令包装在Java代码中的另一个js.executeScript();方法中。之后,您只需调用window.scrollTo(0, window.myScrollHeight);即可使用新变量。

如果仍然无法正常运行,那么我将检查以确保您实际上在呼叫scrolledCommentCount()。这可能是网站无法滚动的另一个原因。

答案 1 :(得分:1)

您可以使用sendKeys方法进行分页。尝试使用此代码。希望有帮助。

JavascriptExecutor js = (JavascriptExecutor)driver;

        while(true){

            Long height=(Long) js.executeScript("return document.body.scrollHeight");
            System.out.println(height);
            Thread.sleep(1000);
            driver.findElement(By.tagName("body")).sendKeys(Keys.END);        

            if (height==0)
            {
                break;
            }               

        } 

答案 2 :(得分:0)

您可以在python中将其编写为

driver.execute_script("window.ScrollBy(0,document.body.scrollHeight)")