selenium窗口切换,获取句柄

演示案例:12306,

需求:点击购票按钮,页面跳转至购票页面,点击跳转页面“登录”按钮时,脚本报错

package com.Demotest;
import org.openqa.jetty.html.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Booking 
{
public static void main(String[] args) throws InterruptedException 
{
// TODO Auto-generated method stub
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();//将窗口最大化
driver.get("http://www.12306.cn");
//点击购票按钮
/*
List<WebElement> elements = driver.findElements(By.tagName("img"));
for (WebElement webElement : elements) 
{
if (webElement.getAttribute("src").contains("http://www.12306.cn/mormhweb/images/ico_gp.gif")) 
{
webElement.click();
Thread.sleep(1000);
break;
}
}
*/
//点击购票
driver.findElement(By.cssSelector("img[alt=\"购票\"]")).click();
//窗口切换,获取窗口句柄
String winHandleBefore = driver.getWindowHandle(); 
for(String winHandle : driver.getWindowHandles())

{     
if (winHandle.equals(winHandleBefore)) 

{
continue;
}
driver.switchTo().window(winHandle); 
break;  
         

//点击登录按钮
driver.findElement(By.id("login_user")).click();

}

}


你可能感兴趣的:(selenium窗口切换,获取句柄)