有没有办法在硒1。X或2。x来滚动浏览器窗口,以便XPath标识的特定元素在浏览器的视图中?在Selenium中有一个focus方法,但在FireFox中它似乎不能物理地滚动视图。有人有什么建议吗?

我需要这个的原因是我正在测试点击页面上的一个元素。不幸的是,除非元素是可见的,否则事件似乎无法工作。我无法控制单击元素时触发的代码,因此无法调试或修改它,因此,最简单的解决方案是将项目滚动到视图中。


当前回答

我使用这种方式滚动元素并单击:

List<WebElement> image = state.getDriver().findElements(By.xpath("//*[contains(@src,'image/plus_btn.jpg')]"));

for (WebElement clickimg : image)
{
  ((JavascriptExecutor) state.getDriver()).executeScript("arguments[0].scrollIntoView(false);", clickimg);
  clickimg.click();
}

其他回答

你可以使用下面的代码片段来滚动:

C#

var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();

好了

我发现元素的边框不正确,导致浏览器滚动到屏幕外。然而,下面的代码对我来说工作得相当好:

private void scrollToElement(WebElement webElement) throws Exception {
    ((JavascriptExecutor)webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded()", webElement);
    Thread.sleep(500);
}

我已经尝试了很多关于滚动的东西,但下面的代码提供了更好的结果。

这将滚动直到元素在视图中:

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

//do anything you want with the element

您可以使用org.openqa.selenium. actions类移动到一个元素。

Java:

WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

Python:

from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()

Javascript

解决方法很简单:

const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);