selenium web driver - switch to parent window

对着背影说爱祢 提交于 2020-01-11 13:12:11

问题


I use selenium Web Driver. I have opened a parent window. After I click on the link the new window opens. I choose some value from the list and this window automatically closes. Now I need to operate in my parent window. How can I do this? I tried the following code:

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

This does not work though.


回答1:


Try this before you click the link that opens the new window:

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



回答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;
}


来源:https://stackoverflow.com/questions/11359118/selenium-web-driver-switch-to-parent-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!