使用Selenium滚动到视口中当前页面上的Web元素的最佳方法是什么

时间:2018-12-28 04:24:38

标签: java selenium selenium-webdriver webdriver webdriverwait

我是自动化的新手,我想知道如何使用Selenium和Java滚动到当前页面上的Web元素。

我尝试了很多在stackoverflow中描述的方法。但是无法解决我的问题。

我尝试过的解决方案:

WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);

3 个答案:

答案 0 :(得分:4)

您可以使用Selenium提供的Actions类。

public void scrollToElement(WebElement element){
    Actions actions = new Actions(driver);
    actions.moveToElement(element);
    actions.perform();
    WebDriverWait wait = new WebDriverWait(driver, 60);
    wait.until(ExpectedConditions.visibilityOf(element));
}

在这里,我添加了一个显式等待,它将等待直到Web元素可见。最长等待时间为60秒。如果Web元素在60秒内不可见,则将引发异常。您可以通过更改此行来增加等待时间。

WebDriverWait wait = new WebDriverWait(driver, 60);

希望这会有所帮助。

答案 1 :(得分:0)

要使用 Selenium Java Viewport中滚动当前页面上的 WebElement ,您需要诱导 WebDriverWait 用于查找元素的可见性,您可以使用以下解决方案:

WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.id("id_of_element")));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element)

答案 2 :(得分:0)

您要将元素从javascript传递到java,然后再传递回javascript。 这是一个坏主意,到它进行往返旅行时,它可能不再存在。

((JavascriptExecutor) driver).executeScript("document.querySelector('#id_of_element').scrollIntoView(true);");

此外,您需要滚动查看很多内容(使用较旧的硒),而不再需要。

相关问题