【问题标题】:Unable to scroll a specific DIV using Selenium WebDriver with Java无法使用 Selenium WebDriver 和 Java 滚动特定的 DIV
【发布时间】:2016-10-02 23:34:35
【问题描述】:

WebDriver 未能找到在浏览器可见区域中不可见的元素。为了使 WebElement 可被 WebDriver 看到,我们需要使该元素在浏览器视图中可见,以便在特定 div 上向下滚动!我尝试了很多,并没有帮助我。因此它仍然无法正常工作。请指教

我的代码:

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", driver.findElement(By.xpath("//*[@id='lobbyMain']/div[3]/div[2]/ul/li[1]/div[1]/h3/a"))).onclick;

【问题讨论】:

  • 你能分享你想滚动的网站吗?
  • @KishanPatel 我无法共享该网站,因为它仍在部署中,尚未上线。
  • 你只是想滚动?
  • @KishanPatel 我想滚动我选择的某个 div
  • 滚动页面?还是滚动下拉?可以给我截图吗?

标签: java selenium automation


【解决方案1】:

当您单击元素时,Selenium 会自动滚动到该元素。你可以这样做:

driver.findElement(By.xpath("//*[@id='lobbyMain']/div[3]/div[2]/ul/li[1]/div[1]/h3/a")).click()

selenium 应该会找到它,滚动到它并单击它。 如果这不起作用,我有时会使用它来滚动:

((JavascriptExecutor) driver).executeScript(
            "scroll(" + element.getLocation().getX() + "," + element.getLocation().getY() + ")");

【讨论】:

    【解决方案2】:

    查看滚动的基本方式是:

    Webelement element = driver.findElement(By.xpath("//*[@id='lobbyMain']/div[3]/div[2]/ul/li[1]/div[1]/h3/a"))
    
    JavascriptExecutor js = (JavascriptExecutor) element;
        int yPosition = element.getLocation().getY();
    
        for (int second = 0;; second++) {
            if(second >=4){
                break;
            }
            ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,200)", ""); //y value '400' can be altered
            Thread.sleep(3000);
    

    您可以根据自己的方便改变秒数。

    否则请参考以下链接。它会帮助你。

    https://www.seleniumeasy.com/selenium-tutorials/scrolling-web-page-with-selenium-webdriver-using-java

    如果您仍然遇到问题,请回复我。 :-)

    【讨论】:

      猜你喜欢
      • 2015-01-27
      • 2015-06-28
      • 2012-03-15
      • 2017-01-03
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      相关资源
      最近更新 更多