WebDriver.getWindowHandle()方法

Ket*_*tan 5 java webdriver selenium-webdriver

我是Selenium学习的新手.WebDriver.getWindowHandle()文档对我来说不是很清楚,并且该示例在本书中没有给出,因此我想到确认此方法返回的值.

1)假设我在第PAGE1页.所以getWindowHandle()应该返回PAGE1的句柄.(正确)

2)现在从这个页面,我转到PAGE2(通过超链接并打开一个新窗口).我的书说现在getWindowHandle()应该返回PAGE2的句柄.但是我的程序仍然返回PAGE1的句柄.

硒v2.43

可在Firefox和Chrome上重现.

问题:getWindowHandle()应返回的确切值是多少?

WebDriver wd = new ChromeDriver();
wd.get("file://D:/Projects/Selenium/Startup/web/ch3/switch_main.html");

String h1 = wd.getWindowHandle();// original handle
System.out.println("First handle = " + h1);

WebElement clickhere = wd.findElement(By.id("clickhere"));
clickhere.click();//moved to a new child page<

String h2 = wd.getWindowHandle();
System.out.println("Second handle = " + h2);// this handle is not different than h1
Run Code Online (Sandbox Code Playgroud)

Chu*_*own 5

getWindowHandle()将获得webDriver当前控制的页面句柄.此句柄是网页的唯一标识符.每次打开页面时都会有所不同,即使它是相同的URL.

getWindowHandles()(不要忘记's')将为您提供Web驱动程序理解的所有页面的所有句柄.请注意,当您将它们放入列表中时,它们将按照打开的顺序列出.

您可以使用SwitchTo().Window("handle")切换到所需的窗口.

SwitchTo().Window("mywindowID")如果您知道窗口ID,则可以使用.

SwitchTo().Window("") 将始终返回基本/主窗口.

SwitchTo().Frame("popupFrame") 将访问来自webdriver当前控制的窗口的Popup.


isa*_*iro 4

如果链接打开一个新窗口,您应该在WebDriver. 您可以使用getWindowHandles循环当前窗口句柄。

请参阅http://www.thoughtworks.com/products/docs/twist/13.3/help/how_do_i_handle_popup_in_selenium2.html中的示例

  String parentWindowHandle = browser.getWindowHandle(); // save the current window handle.
  WebDriver popup = null;
  Iterator<String> windowIterator = browser.getWindowHandles();
  while(windowIterator.hasNext()) { 
    String windowHandle = windowIterator.next(); 
    popup = browser.switchTo().window(windowHandle);
    if (popup.getTitle().equals("Google") {
      break;
    }
  }
Run Code Online (Sandbox Code Playgroud)