我编写了一个简单的代码来使用 Selenium 提交注册表单。提交之前,驱动程序应从主页进入注册页面。
var firefox = new FirefoxDriver();
firefox.Navigate().GoToUrl("http://mywebsite/home");
如果我打印 firefox.Title
,它会正确显示主页标题
在主页上有一个注册按钮。注册按钮链接如下。
<a target="_blank" href="SignUp.jsp">Register Here</a>
为了导航到注册页面,我写了一行:
firefox.FindElement(By.CssSelector("a[href='SignUp.jsp']")).Click();
此后,驱动程序会在 firefox
浏览器的新窗口
中向我显示注册页面。为了将驱动程序导航到注册处,我编写了 firefox.Navigate();
现在如果我打印 firefox.Title
,它会再次显示主页标题。
请帮我找出问题所在。提前致谢。
最佳答案
您几乎捕获了相同的标题
,因为您从未切换到新打开的窗口
// Get the current window handle so you can switch back later.
string currentHandle = driver.CurrentWindowHandle;
// Find the element that triggers the popup when clicked on.
IWebElement element = driver.FindElement(By.XPath("//*[@id='webtraffic_popup_start_button']"));
// The Click method of the PopupWindowFinder class will click
// the desired element, wait for the popup to appear, and return
// the window handle to the popped-up browser window. Note that
// you still need to switch to the window to manipulate the page
// displayed by the popup window.
PopupWindowFinder finder = new PopupWindowFinder(driver);
string popupWindowHandle = finder.Click(element);
driver.SwitchTo().Window(popupWindowHandle);
// Do whatever you need to on the popup browser, then...
driver.Close();
driver.SwitchToWindow(currentHandle);
并且,切换到新窗口后,您应该获得新标题。
但是,这个窗口处理过程对我来说完全令人困惑。 Selenium
.Net
绑定(bind)提供 PopupWindowFinder处理窗口的类。
感谢 JimEvans 的出色作品和 this
关于c# - 使用 C# 将驱动程序导航到 selenium 中新打开的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29038501/