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

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


当前回答

解决方案是:

public void javascriptclick(String element)
{
    WebElement webElement = driver.findElement(By.xpath(element));
    JavascriptExecutor js = (JavascriptExecutor) driver;

    js.executeScript("arguments[0].click();", webElement);
    System.out.println("javascriptclick" + " " + element);
}

其他回答

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

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

您可以使用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()

在滚动的大多数情况下,这段代码都是有效的。

WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));                 
js.executeScript("arguments[0].click();",element);

我同意这里所有人所说的“Selenium有一个隐含的滚动选项”。同样,如果你使用的是Selenium 1,现在你已经升级到Selenium 2,并查找以前版本的命令,你可以使用命令:

Seleniumbackeddriver.

WebDriver driver = new FirefoxDriver();
public void setUp() throws Exception {

    String baseUrl = "http://www.google.co.in/";
    selenium = new WebDriverBackedSelenium(driver, baseUrl);
}

您可以使用这两个版本的命令。

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 +")");