【问题标题】:selenium web driver - switch to parent windowselenium web 驱动程序 - 切换到父窗口
【发布时间】:2012-07-06 17:31:50
【问题描述】:

我使用 selenium Web 驱动程序。我打开了一个父窗口。单击链接后,将打开新窗口。我从列表中选择一些值,此窗口会自动关闭。现在我需要在我的父窗口中操作。我怎样才能做到这一点?我尝试了以下代码:

String HandleBefore = driver.getWindowHandle();
driver.findElement(By.xpath("...")).click();
 for (String Handle : driver.getWindowHandles()) {
        driver.switchTo().window(Handle);}
 driver.findElement(By.linkText("...")).click();
 driver.switchTo().window(HandleBefore);

但这不起作用。

【问题讨论】:

  • 你遍历打开的窗口切换到每个人,最后你继续使用列表中的最后一个......那是为了什么?
  • 我只是不知道切换到子窗口的另一种方式。它对我有用,但我无法切换回父母

标签: java selenium window webdriver switch-statement


【解决方案1】:

在点击打开新窗口的链接之前尝试一下:

parent_h = browser.current_window
# click on the link that opens a new window
handles = browser.window_handles # before the pop-up window closes
handles.remove(parent_h)
browser.switch_to_window(handles.pop())
# do stuff in the popup
# popup window closes
browser.switch_to_window(parent_h)
# and you're back

【讨论】:

  • 我知道这是在 python 中......但你可以将方法翻译成 java
【解决方案2】:

public boolean switchBackParentWindowTitle(String windowTitle){

    boolean executedActionStatus = false;
    try {

        Thread.sleep(1000);
        WebDriver popup = null;
        Set<String> handles = null;

        handles =driver.getWindowHandles();
        Iterator<String> it = handles.iterator();
        while (it.hasNext()){

            String switchWin = it.next();
            popup = driver.switchTo().window(switchWin);

            System.out.println(popup.getTitle());
            if(popup.getTitle().equalsIgnoreCase(windowTitle)){

                log.info("Current switched window title is "+popup.getTitle());
                log.info("Time taken to switch window is "+sw.elapsedTime());
                executedActionStatus = true;
                break;
            }
            else
                log.info("WindowTitle does not found to switch over");
        }
    }
    catch (Exception er) {
        er.printStackTrace();
        log.error("Ex: "+er);
    }   
    return executedActionStatus;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-06
    • 2018-07-15
    • 2019-01-06
    • 2012-09-25
    • 2012-11-28
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    相关资源
    最近更新 更多