java - 如何使用 selenium 在 chrome 中打开新标签

标签 java selenium

我正在尝试在 Selenium 中打开一个新选项卡,但它不起作用。它会在同一选项卡中打开网址。

代码:

        cDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
        cDriver.get(url1);
        cDriver.switchTo().window(tabs.get(1)); 

出现以下异常:

    java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
atcom.freedomoss.crowdcontrol.webharvest.plugin.selenium.RobotPlugin.executePlugin(RobotPlugin.java:187)
at org.webharvest.runtime.processors.WebHarvestPlugin.execute(WebHarvestPlugin.java:125)
at org.webharvest.runtime.processors.BaseProcessor.run(BaseProcessor.java:127)
at org.webharvest.runtime.processors.BodyProcessor.execute(BodyProcessor.java:27)
at org.webharvest.runtime.processors.WebHarvestPlugin.executeBody(WebHarvestPlugin.java:246)
at com.freedomoss.crowdcontrol.webharvest.plugin.selenium.RoboticsFlowPlugin.executePlugin(RoboticsFlowPlugin.java:98)
... 16 more

最佳答案

您可以使用 JavaScript 打开新选项卡

public void openNewTab() {
    ((JavascriptExecutor)driver).executeScript("window.open('about:blank','_blank');");
}

如果您想在新选项卡中执行操作,可以使用:

driver.switchTo().window(); 此方法接受 String 作为参数。确切地说是窗口句柄

你可以像这样获取所有句柄

driver.getWindowHandles()。这将返回当前浏览器中所有句柄的集合。

为了切换到新创建的选项卡,请迭代句柄并使用 switchTo() 方法,如下所示:

    Set<String> handles = driver.getWindowHandles();
    String currentWindowHandle = driver.getWindowHandle();
    for (String handle : handles) {
        if (!currentWindowHandle.equals(handle)) {
            driver.switchTo().window(handle);
        }
    }

警告:如果您有 2 个以上的选项卡,这可能会很棘手。

关于java - 如何使用 selenium 在 chrome 中打开新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48440958/

相关文章:

java - 如何将更新推送到 Primefaces 图表?

java - 以不同的速率从 InputStream 中多次读取

selenium - 如何使用selenium验证目标="_blank"链接?

java - WebDriver等待,不同的等待条件

python - selenium 通过 css 选择器获取元素

python - Selenium:如何在使用 selenium 单击下拉菜单后解析代码

java - SonarQube 通过匿名扫描上传强制身份验证

java - 仅打印 JTable 中带有 Logo 的填充数据

java - 我可以在 Java 中创建只读属性吗?

selenium - org.openqa.selenium.json.JsonException : Expected to read a START_MAP but instead have: END. 通过 Node 执行测试时读取的最后 0 个字符