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

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


当前回答

对我有用的是使用浏览器。在浏览器窗口底部的元素上使用MoveMouseToElement方法。神奇的是,它在ie、Firefox和Chrome浏览器上都能正常运行。

我选择这种方法而不是JavaScript注入技术,只是因为它感觉不那么生硬。

其他回答

def scrollToElement(element: WebElement) = {
  val location = element.getLocation
  driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}

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

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();
}

在Selenium中,我们需要借助JavaScript执行器来滚动到一个元素或滚动页面:

je.executeScript("arguments[0].scrollIntoView(true);", element);

在上面的语句中,元素就是我们需要滚动的元素。我尝试了上面的代码,它对我有用。

我有一个完整的帖子和视频:

http://learn-automation.com/how-to-scroll-into-view-in-selenium-webdriver/

这是JavaScript的重复解决方案,但增加了一个等待元素。

否则,如果正在对元素进行某些操作,可能会出现ElementNotVisibleException。

this.executeJavaScriptFunction("arguments[0].scrollIntoView(true);", elementToBeViewable);
WebDriverWait wait = new WebDriverWait(getDriver(), 5);
wait.until(ExpectedConditions.visibilityOf(elementToBeViewable));

OpenQA。c#中的硒:

WebDriver.ExecuteJavaScript("arguments[0].scrollIntoView({block: \"center\", inline: \"center\"});", Element);

其中WebDriver是新的ChromeDriver(选项)或类似。