如何使用 Selenium 向下滚动?

How to Scroll down with Selenium?

this页面,我需要点击link隐私政策,(它打开一个新对话框),我必须使用 Selenium 向下滚动,并且 Java.

这是我尝试过的:

WebElement element = driver.findElement(By.xpath("/html/body/div[2]"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

它不起作用。 它滚动背景页面而不是活动对话框。

您可以滚动到相对于平面中像素数的位置:

JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript("window.scrollBy(0,450)", "");

您要滚动的 div 具有唯一 ID,您需要先获取对它的引用:

WebElement element = driver.findElement(By.id('document-content'));

之后您可以获得该隐私政策中的最后一个 child div:

List<WebElement> children = element.findElements(By.tagName("div"));
assertTrue(children.size() > 0);
WebElement elementToScrollTo = children.get(children.size()-1);

您现在可以滚动到 elementToScrollTo

要在 link 上使用 隐私政策 调用 click(),您只需引入 WebDriverWait 使所需的 元素可单击 ,然后再次为所需的 引入 WebDriverWait元素可见,然后滚动查看,您可以使用以下解决方案:

  • 代码块:

    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class insly_Privacy_Policy {
    
        public static void main(String[] args) {
    
            System.setProperty("webdriver.gecko.driver", "C:\Utility\BrowserDrivers\geckodriver.exe");
            WebDriver driver=new FirefoxDriver();
            driver.get("https://signup.insly.com/signup");
            new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("privacy policy"))).click();
            WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//div[@id='document-content']//following::div[contains(.,'Revision')]"))));
            ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
        }
    }
    
  • 浏览器快照: