有没有办法在硒1。X或2。x来滚动浏览器窗口,以便XPath标识的特定元素在浏览器的视图中?在Selenium中有一个focus方法,但在FireFox中它似乎不能物理地滚动视图。有人有什么建议吗?
我需要这个的原因是我正在测试点击页面上的一个元素。不幸的是,除非元素是可见的,否则事件似乎无法工作。我无法控制单击元素时触发的代码,因此无法调试或修改它,因此,最简单的解决方案是将项目滚动到视图中。
有没有办法在硒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,但它应该给你一些想法。
其他回答
如果您认为其他答案太俗气,那么这个答案也是,但是这里不涉及JavaScript注入。
当按钮离开屏幕时,它会中断并滚动到它,所以重试它…¯\_()_/¯
try
{
element.Click();
}
catch {
element.Click();
}
使用驱动程序发送键,如下拉键或下拉键,将元素带入视图。我知道这是一个过于简单的解决方案,可能并不适用于所有情况。
瞄准任何元素并发送下键(或上/左/右)似乎也可以工作。我知道这有点像黑客,但我也不太喜欢使用JavaScript解决滚动问题。
例如:
WebElement.sendKeys(Keys.DOWN);
Selenium的默认行为是滚动,因此元素几乎不在视口顶部的视图中。此外,并非所有浏览器都具有完全相同的行为。这很不令人满意。如果您像我一样记录浏览器测试的视频,那么您需要的是元素滚动到视图中并垂直居中。
下面是我的Java解决方案:
public List<String> getBoundedRectangleOfElement(WebElement we)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
List<String> bounds = (ArrayList<String>) je.executeScript(
"var rect = arguments[0].getBoundingClientRect();" +
"return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
System.out.println("top: " + bounds.get(1));
return bounds;
}
然后,为了滚动,你像这样调用它:
public void scrollToElementAndCenterVertically(WebElement we)
{
List<String> bounds = getBoundedRectangleOfElement(we);
Long totalInnerPageHeight = getViewPortHeight(driver);
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}
这招对我很管用:
IWebElement element = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId))[0];
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);