2014-02-07 30 views
0

所以我有一个IE浏览器的驱动程序代码(该网站只与IE工程...):不能切换到其他窗口句柄与webdriver的

PrintStream out; 
try { 
    out = new PrintStream(new FileOutputStream("output.txt")); 
    System.setOut(out); 
} catch (FileNotFoundException e1) { 
    // TODO Auto-generated catch block 
    e1.printStackTrace(); 
} 
System.out.println("Main Handle: " + driver.getWindowHandle()); 

element = driver.findElement(By.id("lnk")); 
element.click(); 

//try { 
// Thread.sleep(1000); 
//} catch (InterruptedException e) { 
// // TODO Auto-generated catch block 
// e.printStackTrace(); 
//} 

try{ 
    for(String winHandle : driver.getWindowHandles()){ 
     System.out.println(winHandle); 
     driver.switchTo().window(winHandle); 
    } 
} 
catch(Exception e){ 
    System.out.println("na bro, unlucky"); 
} 

System.out.println("end"); 

System.out.println(driver.getPageSource()); 

应该有两个窗口句柄,这似乎有来自println。但它只能切换到主窗口,弹出的窗口不能切换到。有两种可能的输出,即使我在同一时间运行该程序。这只是我会得到的机会。第一输出是:

主把手:cd484ff9-3dbd-487d-bfa3-805f19b1ff9d
cd484ff9-3dbd-487d-bfa3-805f19b1ff9d
005d28b9-1c4d-40CF-95ab-1782f2dc53fd

导致的错误:

异常线程“main” org.openqa.selenium.NoSuchWindowException:无法获取浏览器(警告:服务器未提供任何信息栈跟踪)

这意味着它能够切换,但它不存在?这真的很奇怪。第二输出可能是:

主把手:cd9fe661-7257-48ff-93c1-17c89b1f9443
cd9fe661-7257-48ff-93c1-17c89b1f9443
2d96e296-47a2-4cd1-b994-89a2cbe4f045
呐BRO,不幸的

,然后将其转移到打印出主手柄的网页源代码。我不明白为什么它不能抓住第二个手柄?我做错了什么?

回答

0

尝试把一个Thread.sleep代码(10000)之前和之后的代码,切换窗口

try { 
    Thread.sleep(10000); 

    for(String winHandle : driver.getWindowHandles()){ 
     System.out.println(winHandle); 
     driver.switchTo().window(winHandle); 
    } 

    Thread.sleep(10000); 
}catch(InterruptedException e) { 
    e.printstacktrace(); 
}catch(Exception ee){ 
    System.out.println("na bro, unlucky"); 
} 

System.out.println("end"); 
System.out.println(driver.getPageSource()); 

还试图让使用driver.getTitle()的currentwindow的标题,看是否切换成功。

+0

无论延迟多长时间,我都会在'getWindowHandles'中产生一个句柄。出于某种原因,弹出窗口的第二个手柄立即消失。 – Ion