有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用Java在selenium中滚动网页?

我正在尝试滚动使用React JS构建的页面。 即使在使用js.executeScript("scroll(0, 250);");无效后,页面也不会滚动
并尝试滚动该方法,直到某个元素可见


共 (3) 个答案

  1. # 1 楼答案

    您能试试这个吗?我希望您的代码中缺少全局变量window

    // scroll vertically
    js.executeScript("window.scrollTo(0, 1000);") 
    
    // scroll horizontally
    js.executeScript("window.scrollTo(1000, 0);") 
    
    
    //scroll to particular element
    WebElement Element = driver.findElement(By.id("someID"));
    js.executeScript("arguments[0].scrollIntoView();", Element);
    
  2. # 2 楼答案

    您可以使用我编写的以下方法滚动到特定元素。您只需要传递驱动程序对象

    &13; 第13部分,;
    // Method to scroll down to specific element
    public static void scrollToElement(WebDriver driver) throws InterruptedException {
    String key = "";
    WebElement element = null;
    JavascriptExecutor js = (JavascriptExecutor) driver;
    element = driver.findElement(By.xpath(locator));
    // This will scroll the page till the element is found
    js.executeScript("arguments[0].scrollIntoView(true);", element);
    Thread.sleep(2000);
    }
    和#13;
    和#13;
  • # 3 楼答案

    正如你提到的,页面自动刷新2次,然后加载。可能存在问题,因为您试图在首次自动刷新后滚动页面。在这两次自动刷新之间会有微秒的延迟,所以selenium正在尝试滚动页面,但在此之前,站点会自动刷新两次。我可以要求您在使用JavaScript滚动方法之前设置检查点,并进行调试以确保它是否实际工作。如果它真的工作,那么当然你需要执行任何行动后,2自动刷新发生