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

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


当前回答

根据我的经验,当页面上有多个可滚动的部分时,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,但它应该给你一些想法。

其他回答

在页面上随机点一下:

driver.findElement(By.id("ID of a web element present below")).click

然后执行你想做的。

JAVA

尝试滚动到元素利用x y位置,并使用JavascriptExecutor与此是参数:"window。scrollBy (x, y)”。

进口:

import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;

首先你需要获取元素的x y位置。

//initialize element
WebElement element = driver.findElement(By.id("..."));

//get position
int x = element.getLocation().getX();
int y = element.getLocation().getY();

//scroll to x y 
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(" +x +", " +y +")");

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

最简单的解决办法是

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

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

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

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

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

在Java中,我们可以使用JavaScript进行滚动,如下所示:

driver.getEval("var elm = window.document.getElementById('scrollDiv'); if (elm.scrollHeight > elm.clientHeight){elm.scrollTop = elm.scrollHeight;}");

您可以为“elm”分配一个所需的值。scrollTop”变量。