IE9上的Selenium JavascriptExecutor导致'元素没有滚动到视窗中'错误

Selenium JavascriptExecutor on IE9 results in 'element was not scrolled into the viewport' error

本文关键字:滚动 错误 元素 Selenium 上的 JavascriptExecutor 导致 IE9      更新时间:2023-09-26

我正在尝试使用JavascriptExecutor从selenium webdriver打开IE9中的新选项卡:

public void openTab() {
    String url = webDriver.getCurrentUrl();
    String script = "var     a=document.createElement('a');a.target='_blank';a.href='" + url + "';a.innerHTML='open';document.body.appendChild(a);return a";
    Object element = getJSExecutor().executeScript(script);
    if (element instanceof WebElement) {
        WebElement anchor = (WebElement) element;
        anchor.click();
    } else {
        throw new RuntimeException("Unable to open tab: " + url);
    }
}

这在Chrome中工作正常,但在IE9中运行时,我得到以下错误:

ElementNotVisibleException:驱动程序试图点击元素的点没有滚动到视图中。

我使用的是2.31版本的selenium和IEDriverServer。

我在并行虚拟机的IE9中一直遇到这个问题。这是使整个程序工作的两行代码…

Actions builder = new Actions(webDriver);
builder.moveToElement(element).click(element).perform();

将元素滚动到视图中,然后单击它

成功解决了视口问题&让IEDriverServer与两个窗口进行适当的交互,经过一点哄骗,所以我想我会发布我的解决方案,以防其他人有这个问题。

为了解决视口问题,我使用Actions执行moveToElement操作,然后单击:

public void actionsClick(WebElement element){
    Actions builder = new Actions(webDriver);
    builder.moveToElement(element).click(element).perform();
}

IEDriverServer似乎需要更长的时间来拾取所有的窗口句柄,所以我在做点击后添加了5秒等待到openTab方法:

public void openTab() {
    String url = webDriver.getCurrentUrl();
    String script = "var a=document.createElement('a');a.target='_blank';a.href='" + url + "';a.innerHTML='open me in a new tab';document.body.appendChild(a);return a";
    Object element = getJSExecutor().executeScript(script);
    if (element instanceof WebElement) {
        WebElement anchor = (WebElement) element;
        actionsClick(anchor);
        waitFor(5000);
        switchBrowserTab();
        returnToPreviousBrowserTab();
    } else {
        throw new RuntimeException("Unable to open tab: " + url);
    }
}

然后,如上面的方法所示,为了确保IEDriverServer知道两个窗口/选项卡并可以在它们之间移动,我在单击并等待后添加了switchBrowserTab()和returnToPreviousBrowserTab()方法。使用JavascriptExecutor打开一个新选项卡会让焦点留在原来的选项卡上,这个方法被设置为以焦点再次回到那里结束。如果有人以前没有使用过窗口句柄,这里是我用来切换到新打开的选项卡的方法:

    Set<String> handles = webDriver.getWindowHandles();
    List<String> handlesList = new ArrayList<String>();
    for (String handle : handles) {
        handlesList.add(handle);
    }
    webDriver.switchTo().window(handlesList.get(handlesList.size() - 1));
    webDriver.manage().window().maximize();

使用了类似的方法来向后移动,除了我得到当前句柄,然后循环遍历列表以找到它的位置,然后从那里移动到-1句柄。

希望对大家有帮助。

编辑:这适用于IE9和Chrome。未在其他浏览器中测试