2012-02-08 7 views
21

Tengo un problema al automatizar una aplicación web con el controlador web de selenio.¿Cómo puede saber el controlador web de selenio cuándo se ha abierto la nueva ventana y luego reanudar su ejecución?

La página web tiene un botón que al hacer clic se abre en una nueva ventana. Cuando utilizo el siguiente código, que arroja OpenQA.Selenium.NoSuchWindowException: No window found

WebDriver.FindElement(By.Id("id of the button that opens new window")).Click(); 
//Switch to new window 
_WebDriver.SwitchTo().Window("new window name"); 
//Click on button present on the newly opened window 
_WebDriver.FindElement(By.Id("id of button present on newly opened window")).Click(); 

Para resolver el problema anterior añado Thread.Sleep(50000); entre el botón de clic y SwitchTo declaraciones.

WebDriver.FindElement(By.Id("id of the button that opens new window")).Click(); 
Thread.Sleep(50000); //wait 
//Switch to new window 
_WebDriver.SwitchTo().Window("new window name"); 
//Click on button present on the newly opened window 
_WebDriver.FindElement(By.Id("id of button present on newly opened window")).Click(); 

Se resolvió el problema, pero no quiero utilizar la instrucción Thread.Sleep(50000); porque si la ventana toma más tiempo para abrir, el código puede fallar y si la ventana se abre rápidamente y luego se hace la prueba lenta innecesariamente.

¿Hay alguna manera de saber cuándo se ha abierto la ventana y luego la prueba puede reanudar su ejecución?

Respuesta

25

tiene que cambiar el control a la ventana emergente antes de realizar cualquier operación en el mismo. Al usar esto puedes resolver tu problema.

Antes de abrir la ventana emergente, tome el control de la ventana principal y guárdela.

String mwh=driver.getWindowHandle();

Ahora intenta abrir la ventana emergente mediante la realización de alguna acción:

driver.findElement(By.xpath("")).click(); 

Set s=driver.getWindowHandles(); //this method will gives you the handles of all opened windows 

Iterator ite=s.iterator(); 

while(ite.hasNext()) 
{ 
    String popupHandle=ite.next().toString(); 
    if(!popupHandle.contains(mwh)) 
    { 
     driver.switchTo().window(popupHandle); 
     /**/here you can perform operation in pop-up window** 
     //After finished your operation in pop-up just select the main window again 
     driver.switchTo().window(mwh); 
    } 
} 
+0

Gracias por la respuesta. Está funcionando. – Ozone

+1

Puede haber un caso cuando se abre la nueva pestaña pero aún no se ha agregado el mango a la instancia de la unidad. Mi solución es antes de hacer clic en obtener el conteo actual del controlador y luego en el interior mientras compruebo si el conteo ha cambiado. Solo entonces, cambie a la pestaña recién abierta como esta 'driver.switchTo(). Window (maneja [handles.count() - 1]);' donde 'handle' se actualiza en cada iteración. – Edgar

9

Se podía esperar hasta que la operación tiene éxito, por ejemplo, en Python:

from selenium.common.exceptions import NoSuchWindowException 
from selenium.webdriver.support.ui import WebDriverWait 

def found_window(name): 
    def predicate(driver): 
     try: driver.switch_to_window(name) 
     except NoSuchWindowException: 
      return False 
     else: 
      return True # found window 
    return predicate 

driver.find_element_by_id("id of the button that opens new window").click()   
WebDriverWait(driver, timeout=50).until(found_window("new window name")) 
WebDriverWait(driver, timeout=10).until(# wait until the button is available 
    lambda x: x.find_element_by_id("id of button present on newly opened window"))\ 
    .click() 
+0

Gracias por la respuesta. – Ozone

1

fin encontré la respuesta, he usado el método siguiente para cambiar a la nueva ventana,

public String switchwindow(String object, String data){ 
     try { 

     String winHandleBefore = driver.getWindowHandle(); 

     for(String winHandle : driver.getWindowHandles()){ 
      driver.switchTo().window(winHandle); 
     } 
     }catch(Exception e){ 
     return Constants.KEYWORD_FAIL+ "Unable to Switch Window" + e.getMessage(); 
     } 
     return Constants.KEYWORD_PASS; 
     } 

Para moverme a la ventana principal, utilicé el siguiente código,

public String switchwindowback(String object, String data){ 
      try { 
       String winHandleBefore = driver.getWindowHandle(); 
       driver.close(); 
       //Switch back to original browser (first window) 
       driver.switchTo().window(winHandleBefore); 
       //continue with original browser (first window) 
      }catch(Exception e){ 
      return Constants.KEYWORD_FAIL+ "Unable to Switch to main window" + e.getMessage(); 
      } 
      return Constants.KEYWORD_PASS; 
      } 

Creo que esto le ayudará a cambiar entre las ventanas.

1

Lo uso para esperar a que se abra la ventana y funciona para mí.

código C#:

public static void WaitUntilNewWindowIsOpened(this RemoteWebDriver driver, int expectedNumberOfWindows, int maxRetryCount = 100) 
    { 
     int returnValue; 
     bool boolReturnValue; 
     for (var i = 0; i < maxRetryCount; Thread.Sleep(100), i++) 
     { 
      returnValue = driver.WindowHandles.Count; 
      boolReturnValue = (returnValue == expectedNumberOfWindows ? true : false); 
      if (boolReturnValue) 
      { 
       return; 
      } 
     } 
     //try one last time to check for window 
     returnValue = driver.WindowHandles.Count; 
     boolReturnValue = (returnValue == expectedNumberOfWindows ? true : false); 
     if (!boolReturnValue) 
     { 
      throw new ApplicationException("New window did not open."); 
     } 
    } 

y luego me llama a este método en el código

Extensions.WaitUntilNewWindowIsOpened(driver, 2); 
Cuestiones relacionadas