无法在Windows之间切换 - 无法显示浏览器消息

时间:2014-08-05 08:27:22

标签: java selenium selenium-webdriver

点击主窗口中的按钮后,我试图点击新打开的浏览器窗口中的按钮。每次显示消息时:

  

无法在关闭的窗口中找到元素

以下是我正在使用的代码:

public  Manage Administrators() {
 String parentWindow = driver.getWindowHandle();
 clickButton(waitUntilElementIsPresent(driver.findElement(By.xpath("//span[contains(text(),'Administrators')]"))));
  Set<String> handles =  driver.getWindowHandles();
    for(String windowHandle  : handles)
        {
        if(!windowHandle.equals(parentWindow))
           {
           driver.switchTo().window(windowHandle);
          clickButton(Users);

          driver.switchTo().window(parentWindow); 
           }
        }
 return PageFactory.initElements(driver, Manage.class);

似乎新窗口打开,但Selenium看不到。

1 个答案:

答案 0 :(得分:1)

您必须等待新窗口打开。这可以通过以下方式完成:

String parentWindow = driver.getWindowHandle();
int prevWndCount = driver.getWindowHandles().size();
clickButton(waitUntilElementIsPresent(driver.findElement(By.xpath("//span[contains(text(),'Administrators')]"))));

// Waits for 60 seconds
WebDriverWait wait = new WebDriverWait(driver, 60);

// Wait until expected condition (Window count increases) met
wait.until((ExpectedCondition<Boolean>) new ExpectedCondition<Boolean>() {

   public Boolean apply(WebDriver d) {

      // Return true if window count increases, else return false
      return d.getWindowHandles().size() > prevWndCount;

   }

});
Set<String> handles =  driver.getWindowHandles();
for(String windowHandle  : handles)
   {
      if(!windowHandle.equals(parentWindow))
      {
        driver.switchTo().window(windowHandle);
        clickButton(Users);
        driver.switchTo().window(parentWindow); 
      }
   }

return PageFactory.initElements(driver, Manage.class);

看看这是否有帮助!