2014-02-07 28 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