WebDriver.getWindowHandle() 方法

2022-01-16 00:00:00 selenium-webdriver webdriver java

我是 Selenium 学习的新手.WebDriver.getWindowHandle() documentation 对我来说不是很清楚,并且该示例无法按书中给出的那样工作,因此我想确认此方法返回的值.

I'm new to Selenium learning. WebDriver.getWindowHandle() documentation is not very clear to me and the example is not working as given in the book, so I thought of confirming the value returned by this method.

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

1) Let's say I am on page PAGE1. So getWindowHandle() should return handle to PAGE1. (Correct)

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

2) Now from this page, I go to PAGE2 (by hyperlink and opening a new window). My book says now getWindowHandle() should return handle to PAGE2. However my program still returns handle to PAGE1.

硒 v2.43

可在 Firefox 和 Chrome 上重现.

Reproducible on Firefox and Chrome both.

问题: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

<代码>

推荐答案

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

getWindowHandle() will get the handle of the page the webDriver is currently controlling. This handle is a unique identifier for the web page. This is different every time you open a page even if it is the same URL.

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

getWindowHandles() (don't forget the 's') will give you all the handles for all the pages that the web driver understands are open. Note that when you put these in a list they are listed in the order that they have been opened.

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

You can use SwitchTo().Window("handle") to switch to the window you desire.

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

You can use SwitchTo().Window("mywindowID"), if you know the window ID.

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

SwitchTo().Window("") will always go back to the base/main window.

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

SwitchTo().Frame("popupFrame") will get to the Popup that came from the window the webdriver is currently controlling.

相关文章