如何在WebDriver中使用Java将浏览器控件带到新打开的选项卡中

时间:2015-08-04 06:52:41

标签: java selenium-webdriver automation

//Go to a page where link is present 
driver.findElement(By.xpath("//div[@id='LftNav']/ul/li[3]/div/ul/li[3]/a/label"))).click();
//Click this link will open up a new tab.     
driver.findElement(By.xpath("//tr[2]/td[9]/a")).click();

//Now I have to verify a value present in the New Tab.

为此我必须将Control传递给New Tab。我该怎么办?

3 个答案:

答案 0 :(得分:2)

您可以使用以下功能切换标签页(和完整的窗口):

ArrayList<String> windowHandles = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(windowHandles.get(1));

exept你只有两个手柄。如果要关闭选项卡并返回,可以使用:

driver.close();
driver.switchTo().window(windowHandles.get(0));

如果您有两个以上的标签,可以使用:

driver.getWindowHandles().size()

获取已打开标签的数量,然后跳转到size()-1

答案 1 :(得分:0)

String mainWindow = driver.getWindowHandle(); // get the main window handle
driver.findElement(By.cssSelector("//*[#id='someId']")).click(); // click some link that opens a new window

for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle);
 // switch focus of WebDriver to the next found window handle (that's your newly opened window)
if(driver.findElement(By.Id("SomeID")).getText().equals("expected window title"))
break;
}

答案 2 :(得分:0)

SendKeys对我不起作用。我尝试了以下对我有用的代码:

WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
Robot robot = new Robot();
robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);  
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);  
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_TAB);
int tabNo = driver.getWindowHandles().size();
System.out.println(tabNo);
ArrayList<String> windowHandles = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(windowHandles.get(tabNo-1)); 
driver.get("http://www.bing.com/");