Selenium webdriver窗口处理c#switchTo失败

use*_*331 5 c# selenium for-loop webdriver window-handles

测试期间会弹出2个窗口.

我的代码:

string BaseWindow = driver.CurrentWindowHandle;                 
ReadOnlyCollection<string> handles = driver.WindowHandles;

foreach(string handle in handles)                    
{                         
    Boolean a = driver.SwitchTo().Window(handle).Url.Contains("Main");
    if (a == true)  
    {       
        InitialSetting.driver.SwitchTo().Window(handle);      
        break;
    }  
}                
Run Code Online (Sandbox Code Playgroud)

我想切换到url包含"Main"的窗口.但是当测试运行时,它会在两个窗口之间连续切换并且不会停止.

我调试,发现foreach即使boolean a是真的也没有收支平衡.

我该如何解决这个问题?

小智 12

//switch to new window 
driver.FindElement(By.Id("link")).Click(); 

//wait for new window to open 
Thread.Sleep(2000); 

//get the current window handles 
string popupHandle = string.Empty; 
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;  

foreach (string handle in windowHandles)  
{  
    if (handle != existingWindowHandle)  
    {  
         popupHandle = handle; break;  
    }  
}  

 //switch to new window 
driver.SwitchTo().Window(popupHandle); 

//check for element on new page 
webElement = driver.FindElement(By.Id("four04msg")); 
if(webElement.Text == "THE CONTENT YOU REQUESTED COULDN’T BE FOUND...")  
{  
    return false;  
}  
else  
{  
    return true;  
}  

 //close the new window to navigate to the previous one
driver.close(); 

//switch back to original window 
driver.SwitchTo().Window(existingWindowHandle);
Run Code Online (Sandbox Code Playgroud)