使用 C# 在 selenium 中导航 driver 到新打开的 window

Navigate driver to new opened window in selenium with C#

我编写了一个简单的代码来使用 Selenium 提交注册表单。提交前,driver 应该从首页到注册页面。

var firefox = new FirefoxDriver();
firefox.Navigate().GoToUrl("http://mywebsite/home");

如果我打印 firefox.Title,它会显示当前主页的标题

并且在主页中,有一个 sign-up 按钮。注册按钮 link 如下所示。

<a target="_blank" href="SignUp.jsp">Register Here</a>

为了导航到注册页面,我写了一行:

firefox.FindElement(By.CssSelector("a[href='SignUp.jsp']")).Click();

之后,driver 向我展示了 firefox 浏览器的 new window 中的注册页面。要导航 driver 到我写的注册 firefox.Navigate();

现在 如果我打印 firefox.Title,它会再次显示主页标题

请帮我找出问题所在。提前致谢。

使用

firefox.SwitchTo().Window(handle);

其中 handle 是在 firefox.WindowHandles 中找到的实例之一。这将在不同的 window 实例之间切换。您可以在 IWebDriver.SwitchTo().

的文档中找到更多信息

你几乎抓住了同样的东西 title 因为你从未切换到新开的 window

// 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);

并且,在切换到新的 window 之后,您应该会获得新的头衔。

但是,这个 window 处理过程让我非常困惑。 Selenium .Net 绑定提供 PopupWindowFinder class 来处理 windows。

感谢 JimEvans 的出色作品和 this