有没有办法在硒1。X或2。x来滚动浏览器窗口,以便XPath标识的特定元素在浏览器的视图中?在Selenium中有一个focus方法,但在FireFox中它似乎不能物理地滚动视图。有人有什么建议吗?
我需要这个的原因是我正在测试点击页面上的一个元素。不幸的是,除非元素是可见的,否则事件似乎无法工作。我无法控制单击元素时触发的代码,因此无法调试或修改它,因此,最简单的解决方案是将项目滚动到视图中。
有没有办法在硒1。X或2。x来滚动浏览器窗口,以便XPath标识的特定元素在浏览器的视图中?在Selenium中有一个focus方法,但在FireFox中它似乎不能物理地滚动视图。有人有什么建议吗?
我需要这个的原因是我正在测试点击页面上的一个元素。不幸的是,除非元素是可见的,否则事件似乎无法工作。我无法控制单击元素时触发的代码,因此无法调试或修改它,因此,最简单的解决方案是将项目滚动到视图中。
当前回答
你可以使用下面的代码片段来滚动:
C#
var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();
好了
其他回答
根据我的经验,当页面上有多个可滚动的部分时,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,但它应该给你一些想法。
我同意这里所有人所说的“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);
}
您可以使用这两个版本的命令。
Javascript
解决方法很简单:
const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);
我发现元素的边框不正确,导致浏览器滚动到屏幕外。然而,下面的代码对我来说工作得相当好:
private void scrollToElement(WebElement webElement) throws Exception {
((JavascriptExecutor)webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded()", webElement);
Thread.sleep(500);
}
在页面上随机点一下:
driver.findElement(By.id("ID of a web element present below")).click
然后执行你想做的。