Selenium 弹出框 OR 弹出页面


弹出框

Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggerd and action that would open a popup, you can access the alert with the following:

Alert alert = driver.switchTo().alert();

This will return the currently open alert object. With this object you can now accept, dismiss, read it’s contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the JavaDocs for more information.

弹出页面

1.

WebDriver driver = new FirefoxDriver(); 
String baseUrl = "http://www.google.com";
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

弹出页面

Selenium selenium = new WebDriverBackedSelenium(driver, "aaaaaaaaa");
selenium.selectWindow(selenium.getAllWindowTitles()[1]);

序数从0开始,1自然是新弹出的窗口

这时selenium可以定位到新弹出页面,也可以继续操作原页面,但是这个方法只适用于firefox,如果用Ie的话会报错

2.

Moving Between Windows and Frames

It's rare for a modern web application not to have any frames or to be constrained to a single window. WebDriver supports moving between named windows using the "switchTo" method:

driver.switchTo().window("windowName");

All calls to driver will now be interpreted as being directed to the particular window. But how do you know the window's name? Take a look at the javascript or link that opened it:

Click here to open a new window

Alternatively, you can pass a "window handle" to the "switchTo().window()" method. Knowing this, it's possible to iterate over every open window like so:

for (String handle : driver.getWindowHandles()) {
  driver.switchTo().window(handle);}

You can also swing from frame to frame (or into iframes):

driver.switchTo().frame("frameName");

It's possible to access subframes by chaining switchTo() calls, and you can specify the frame by its index too. That is:

driver.switchTo().frame("frameName")
      .switchTo().frame(0)
      .switchTo().frame("child");

would go to the frame named "child" of the first subframe of the frame called "frameName". All frames are evaluated as if from currently switched to frame. To get back to the top level, call:

driver.switchTo().defaultContent();

其实上面还没有搞太懂

不过找到一个解决目前问题的办法:

String windowId = "";
        for (String handle : driver.getWindowHandles()) {
            if (driver.switchTo().window(handle).getTitle().contains("登录中心")) {
                windowId = handle;
                break;
            }else driver.close();        }
        driver.switchTo().window(windowId);
         login();

这样子得到想要的页面的windowId,然后定位到那个页面上进行操作,对于不需要的页面可以用driver.close()关掉。

Joyce /
Published under (CC) BY-NC-SA in categories selenium  tagged with selenium