java 网页切换_如何使用Selenium WebDriver与Java切换到另一个选项卡

在我看来,driver.getWindowHandles()不适用于标签…你总是会使用CURRENT标签的句柄返回一个项目数组… [删除旧答案,因为这似乎现在已修复]

更新(2016年6月16日):当前版本的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 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时,Actions根本无法正常工作. [更新6/11/2016]:Firefox通过geckodriver现在返回一个Set]

你也可以做这样的事情..把它投射到ArrayList:

// set tab_index to the number of window/tab you want. 0 is the first tab

ArrayList tabs_windows = new ArrayList (driver.getWindowHandles());

driver.switchTo().window(tabs_windows.get(tab_index));

更新:为了解决geckodriver错误,我已经切换到使用element.sendkeys …这样的东西似乎在Marionette和Chrome中工作..(Update2):由于Selenium 3.0.1中的更改​​而更新为javascript:

// driver.findElement(By.cssSelector("body")).sendKeys(Keys.chord(Keys.CONTROL, "t"));

((JavascriptExecutor)driver).executeScript("window.open('about:blank', '_blank');");

Set 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());

更新(2016年11月16日):使用Ctrl-W关闭的旧方法似乎也被破坏了…使用这个:

((JavascriptExecutor)driver).executeScript("close();");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值