【问题标题】:JavascriptExecutor not performing the scroll actionJavascriptExecutor 不执行滚动操作
【发布时间】:2019-08-28 08:19:58
【问题描述】:

我正在对 youtube 视频进行自动化测试;以这个为例-https://www.youtube.com/watch?v=AjWfY7SnMBI。 我想向下滚动页面以检查 cmets 是否加载。但是 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");

【问题讨论】:

    标签: javascript java selenium


    【解决方案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;
                }               
    
            } 
    

    【讨论】:

    • 是什么让你说 window.scrollTo() 不起作用?我用 YouTube 测试了我的解决方案,它像 OP 要求的那样向下滚动到 cmets 部分
    • 那太好了。这是另一种选择。
    • 感谢两位的意见!第一个选项仍然对我不起作用(我正在使用 Chrome),我确信脚本已执行,因为我从最后一个方法行中看到了“滚动”打印语句。但是,页面上没有可见的操作。我实现了 Kajal 的解决方案,我可以看到页面正在向下滚动并加载 cmets。
    【解决方案2】:

    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()。这可能是网站无法滚动的另一个原因。

    【讨论】:

      【解决方案3】:

      你可以在 python 中这样写

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多