导出文档时窗口关闭,无法切换到父窗口

时间:2018-10-13 07:13:49

标签: java selenium testing

我正在IE浏览器上进行测试。单击子窗口中的“导出”按钮后,子窗口关闭并保存并打开下载,然后在IE中弹出。此后,我已使用机械手类切换到弹出窗口,然后单击保存选项以下载文件,如图所示。但是单击后,我想返回到父窗口,但显示“窗口已关闭”,无法这样做。 enter image description here

     String parent= driver.getWindowHandle();

    for (String child : driver.getWindowHandles()) {

        if(!parent.equalsIgnoreCase(child))
        {

        driver.switchTo().window(child);


        if(browser.equals("chrome"))
        {
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(.,'Export')]"))).click();
        }
        else if(browser.equals("IE"))
        {
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(.,'Export')]")));

            WebElement ele=driver.findElement(By.xpath("//a[contains(.,'Export')]"));

            myRobot.DownloadFileInIEBrowser(driver, ele);   
        }
        }
    }
   System.out.println("current handles"+driver.getWindowHandle());
   driver.switchTo().window(parent);

 public class myRobot {

public static void DownloadFileInIEBrowser(WebDriver driver,WebElement ele) throws AWTException, InterruptedException
{

    Robot robot = new Robot();
   //get the focus on the element..don't use click since it stalls the driver          
    new Actions(driver).moveToElement(ele).perform();

    Thread.sleep(3000);
    Actions action = new Actions(driver);
    action.contextClick(ele).build().perform(); //right click on focus element
    Thread.sleep(5000);



    for(int i=0;i<2;i++)
    {
   robot.keyPress(KeyEvent.VK_ENTER);         
   robot.keyRelease(KeyEvent.VK_ENTER);
    }
   robot.delay(2000);
   /*robot command to move cursor to dialog pop up window
    * Ctrl+F6 pressed to move cursor to pop up dailog window in IE while downloading
    * Three times Tab button is pressed to focus cursor on Save button
    * Hit Enter again to save file
    */
   robot.keyPress(KeyEvent.VK_CONTROL);
   robot.keyPress(KeyEvent.VK_F6);
   robot.keyRelease(KeyEvent.VK_F6);
   robot.keyRelease(KeyEvent.VK_CONTROL);
   for(int i=0;i<3;i++)
   {
   robot.keyPress(KeyEvent.VK_TAB);
   robot.keyRelease(KeyEvent.VK_TAB);
   }
   robot.keyPress(KeyEvent.VK_ENTER);
   robot.keyRelease(KeyEvent.VK_ENTER);

}

}

1 个答案:

答案 0 :(得分:0)

首先-根据我的经验,getWindowHandles()会花费一些时间。

第二个-最好将getWindowHandles()设为ArrayList

第三-切换到WindowHandle而不是父级。

ArrayList<String> winHandles = new ArrayList<String> (driver.getWindowHandles());
Thread.sleep(500);
driver.switchTo().window(winHandles.get(1));
// driver.switchTo().window(winHandles.get(0));