【问题标题】:WebDriver - Switch to new Window and selecting dropdown is not working in IEWebDriver - 切换到新窗口并选择下拉菜单在 IE 中不起作用
【发布时间】:2016-05-13 18:30:37
【问题描述】:

尝试切换到新窗口选项卡然后从下拉列表中选择一个项目不起作用..

public static void handleNewTabWindow() {
    driver.findElement(By.xpath(".//img[@src='/images/buttons/gl_upload.gif']")).click();
    String Parent_Window = driver.getWindowHandle();
    for (String Child_Window : driver.getWindowHandles()) {
        driver.switchTo().window(Child_Window);
        WebElement dropdown = getWhenVisible(By.xpath(".//select[@name='UPLOAD_ORG_ID']"));
        dropdown.click();
        getWhenVisible(By.xpath(".//option[contains(text(), 'CI Borrower')]")).click();
    }
    driver.switchTo().window(Parent_Window);
    driver.close();
}

【问题讨论】:

    标签: selenium webdriver dropdown


    【解决方案1】:

    您必须等到屏幕上出现一个新窗口才能切换到它。您的代码试图在单击按钮后立即切换,在几毫秒内 - 浏览器不是那么快,您必须等待几秒钟左右。

    一个不太优雅但快速的解决方案是在此处引入固定的Thread.sleep( 2000 );

    driver.findElement(By.xpath(".//img[@src='/images/buttons/gl_upload.gif']")).click();
    Thread.sleep( 2000 );
    String Parent_Window = driver.getWindowHandle();
    

    但这不是很好。


    更好的解决方案是实现一种方法,该方法将等到屏幕上出现新窗口(但不超过某个固定超时 - 例如 30-60 秒)。例如,我们项目中最常用的方法之一是等待具有给定标题的窗口的方法,如下所示(代码框架):

    void waitForWindowWithTitleAndSwitchToIt( String windowTitle, int timeoutInSeconds ){
       .... 
       while( timeout-not-expired ){
          handles = driver.getWindowHandles():
          for( String handle: handles ){
             driver.switchTo.window( handle );
             if( driver.getTitle().contains( windowTitle ) ){
                 // found a window with a given title
                 return;
             }
          }
          sleep( for a 1-2 seconds ); 
          // and try again 
       }
       throw new TimeoutException(
              String.format("A browser window named %s doesn't appear on the screen", windowTitle )
              );
       }
    

    我们在我们的项目中实现了几个这样的方法,它们使用不同的标准等待新窗口:等待具有给定确切标题的窗口,等待标题包含给定子字符串的窗口,等待具有给定子字符串的窗口页面源中的给定字符串,用于在 url 中具有给定(子)字符串的窗口等。

    【讨论】:

      猜你喜欢
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      • 2011-09-21
      • 1970-01-01
      • 2013-06-24
      相关资源
      最近更新 更多