c# - 使用 C# 将驱动程序导航到 selenium 中新打开的窗口

标签 c# firefox selenium-webdriver

我编写了一个简单的代码来使用 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/

相关文章:

c# - 使用 SqlDependency 导致不断更新

java - Selenium 中的 Apache POI 文本格式不佳

c# - 构造函数过度注入(inject)类型专注于收集数据

javascript - 如何捕获 Firefox 中未保存更改的 "Stay on Page"按钮?

css - CSS 中的 Data-URI SVG 背景在 Firefox 中不起作用

html - 是否有任何(阴影?)css 属性用于在提交输入中文本周围的间距?

android - By和MobileBy的区别

java - 如何从 testNG 测试计划中传递 invocationCount 的值

c# - 如何开始使用 ASP.Net MVC 4/Azure 和 MonoDevelop?

C# 和 Excel 最佳实践