我在使用Selenium WebDriver自动化一个Web应用程序时遇到了问题。
当页面上有一个按钮,点击该按钮会打开一个新窗口。当我使用以下代码时,它会抛出 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();
为了解决上述问题,我在按钮单击和 SwitchTo
语句之间添加了 Thread.Sleep(50000);
。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();
这解决了问题,但我不想使用Thread.Sleep(50000);
语句,因为如果窗口打开需要更长时间,代码就会失败;如果窗口快速打开,则会不必要地使测试变慢。
有没有办法知道窗口何时打开,然后测试可以恢复其执行?
driver.switchTo().window(handles[handles.count() - 1]);
,其中handles
在每次迭代中都会更新。 - Mr. BlondWebDriverWait.until()
函数内部进行。 - Marinos An