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

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


当前回答

如果您认为其他答案太俗气,那么这个答案也是,但是这里不涉及JavaScript注入。

当按钮离开屏幕时,它会中断并滚动到它,所以重试它…¯\_()_/¯

try
{
    element.Click();
}
catch {
    element.Click();
}

其他回答

根据我的经验,当页面上有多个可滚动的部分时,Selenium Webdriver不会在单击时自动滚动到一个元素(这是很常见的)。

我使用Ruby,对于我的AUT,我必须猴子补丁点击方法如下;

class Element

      #
      # Alias the original click method to use later on
      #
      alias_method :base_click, :click

      # Override the base click method to scroll into view if the element is not visible
      # and then retry click
      #
      def click
        begin
          base_click
        rescue Selenium::WebDriver::Error::ElementNotVisibleError
          location_once_scrolled_into_view
          base_click
        end
      end

location_once_scrolled_into_view方法是WebElement类上已有的方法。

我理解你可能不使用Ruby,但它应该给你一些想法。

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

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

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

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

我不确定这个问题是否仍然相关,但在参考https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView的scrollIntoView文档后。

最简单的解决办法是

executor.executeScript("arguments[0].scrollIntoView({block: \"center\",inline: \"center\",behavior: \"smooth\"});",element);

这将把元素滚动到页面中央。

这段代码为我工作:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.scrollBy(250, 350)");