我正在打开 google.com,然后单击“GMail”超链接,在同一浏览器中打开一个新选项卡。
现在我想切换到使用 Selenium WebDriver 打开 GMail 的新选项卡。
代码片段是:
WebDriver wd = new ChromeDriver();
wd.get("https://www.google.co.in/?gws_rd=ssl");
wd.findElement(By.linkText("Gmail")).sendKeys(Keys.CONTROL,Keys.RETURN);
现在我想转到我打开 GMail 链接的选项卡。我在谷歌上搜索了 N 种解决方案,但没有一个有效。
例如
解决方案 1:
String Tab1 = wd.getWindowHandle();
ArrayList<String> availableWindows = new ArrayList<String>(wd.getWindowHandles());
if (!availableWindows.isEmpty()) {
wd.switchTo().window(availableWindows.get(1));
}
解决方案 2:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
请建议。我坚持这一点。
最佳答案
在我看来 driver.getWindowHandles() 不适用于选项卡......你总是会得到一个带有 CURRENT 选项卡句柄的项目数组...... [删除旧答案因为这似乎现在已修复]
更新(6/16/2016):当前版本的 Selenium(独立服务器 2.53.0)似乎表现不同。现在我正在使用类似这样的方法打开/切换驱动程序到新选项卡:
更新(2016 年 11 月 16 日):Selenium 3.0.1 似乎又发生了变化?我现在必须使用 javascript 打开一个新选项卡。这似乎只在 Chrome 中有效... Firefox 打开一个新窗口。我将看看是否可以使用 geckodriver 的设置(功能/配置文件?)更改该行为。
// Actions actions = new Actions(driver);
// actions.keyDown(Keys.CONTROL).sendKeys("t").keyUp(Keys.CONTROL).build().perform();
((JavascriptExecutor)driver).executeScript("window.open('about:blank', '_blank');");
Set<String> tab_handles = driver.getWindowHandles();
int number_of_tabs = tab_handles.size();
int new_tab_index = number_of_tabs-1;
driver.switchTo().window(tab_handles.toArray()[new_tab_index].toString());
getWindowHandles() 方法现在返回一个 Set。到目前为止,这仅在 Chrome 中进行过测试,因为 Firefox 版本 47 目前在使用 firefoxdriver 时存在一些严重问题......并且使用 geckodriver 时,操作根本不起作用。 [更新 6/11/2016]:Firefox 通过 geckodriver 现在返回一个集合]
你也可以这样做..将它转换为 ArrayList:
// set tab_index to the number of window/tab you want. 0 is the first tab
ArrayList<String> tabs_windows = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs_windows.get(tab_index));
更新:为了解决 geckodriver 错误,我已经切换到使用 element.sendkeys...类似这样的东西似乎在 Marionette 和 Chrome 中工作。(更新 2):由于 Selenium 3.0 中的更改而更新为 javascript。 1:
// driver.findElement(By.cssSelector("body")).sendKeys(Keys.chord(Keys.CONTROL, "t"));
((JavascriptExecutor)driver).executeScript("window.open('about:blank', '_blank');");
Set<String> tab_handles = driver.getWindowHandles();
int number_of_tabs = tab_handles.size();
int new_tab_index = number_of_tabs-1;
driver.switchTo().window(tab_handles.toArray()[new_tab_index].toString());
更新(11/16/2016):使用 Ctrl-W 关闭的旧方法似乎也被打破了......使用这个:
((JavascriptExecutor)driver).executeScript("close();");
关于java - 如何使用带有 Java 的 Selenium WebDriver 切换到另一个选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29455355/