【问题标题】:How to switch between two windows in browser using Selenium java如何使用 Selenium java 在浏览器中的两个窗口之间切换
【发布时间】:2013-10-07 16:55:18
【问题描述】:

我正在使用 Selenium Automation。在此,当我单击当前窗口中的链接时,将打开一个新窗口。我只想将控件切换到新窗口。但我不能这样做。实际上新窗口是自动生成的。也就是动态生成链接。朋友们帮帮我……

【问题讨论】:

    标签: java testing selenium browser selenium-webdriver


    【解决方案1】:

    摘自 github 上的 getting started with selenium webdriver 项目,

        /**
         * Waits for a window to appear, then switches to it.
         * @param regex Regex enabled. Url of the window, or title.
         * @return
         */
        public AutomationTest waitForWindow(String regex) {
            Set<String> windows = driver.getWindowHandles();
    
            for (String window : windows) {
                try {
                    driver.switchTo().window(window);
    
                    p = Pattern.compile(regex);
                    m = p.matcher(driver.getCurrentUrl());
    
                    if (m.find()) {
                        attempts = 0;
                        return switchToWindow(regex);
                    }
                    else {
                        // try for title
                        m = p.matcher(driver.getTitle());
    
                        if (m.find()) {
                            attempts = 0;
                            return switchToWindow(regex);
                        }
                    }
                } catch(NoSuchWindowException e) {
                    if (attempts <= MAX_ATTEMPTS) {
                        attempts++;
    
                        try {Thread.sleep(1);}catch(Exception x) { x.printStackTrace(); }
    
                        return waitForWindow(regex);
                    } else {
                        fail("Window with url|title: " + regex + " did not appear after " + MAX_ATTEMPTS + " tries. Exiting.");
                    }
                }
            }
    
            // when we reach this point, that means no window exists with that title..
            if (attempts == MAX_ATTEMPTS) {
                fail("Window with title: " + regex + " did not appear after 5 tries. Exiting.");
                return this;
            } else {
                System.out.println("#waitForWindow() : Window doesn't exist yet. [" + regex + "] Trying again. " + attempts + "/" + MAX_ATTEMPTS);
                attempts++;
                return waitForWindow(regex);
            }
        }
    
        /**
         * Switch's to a window that is already in existance.
         * @param regex Regex enabled. Url of the window, or title.
         * @return
         */
        public AutomationTest switchToWindow(String regex) {
            Set<String> windows = driver.getWindowHandles();
    
            for (String window : windows) {
                driver.switchTo().window(window);
                System.out.println(String.format("#switchToWindow() : title=%s ; url=%s",
                        driver.getTitle(),
                        driver.getCurrentUrl()));
    
                p = Pattern.compile(regex);
                m = p.matcher(driver.getTitle());
    
                if (m.find()) return this;
                else {
                    m = p.matcher(driver.getCurrentUrl());
                    if (m.find()) return this;
                }
            }
    
            fail("Could not switch to window with title / url: " + regex);
            return this;
        }
    

    这些是帮助您入门的 2 个自定义函数。或者您可以从 github 上查看该项目,以使您的 selenium 项目设计得更好、更容易。

    这些函数可以切换到或等待(如果它不存在)具有特定标题/url的窗口。

    【讨论】:

    • 确保将“AutomationTest”变量更改为void。这种方法已经过验证,并且有效。它在你身边,它不起作用。如果您想要工作副本,请下载the project that this is from 并将其导入 eclipse 中查看。
    • 它在src/tests/java 下的SampleFunctionalTest 类中。它从57 行开始
    • 终于成功了,先生。我使用了我在回答中提到的一些代码。请看看它,并给我你的反馈先生。谢谢..!!
    【解决方案2】:

    是的,这是可能的。首先你需要将引用保存到当前窗口。

    String parentWindow= driver.getWindowHandle();
    

    点击链接后,需要切换到其他窗口。

    List<String> allWindows = driver.getWindowHandles();
    for(String curWindow : allWindows){
        driver.switchTo().window(curWindow);
    }
    

    这是你对新窗口执行操作的地方,最后用

    关闭它
    driver.close();
    

    并切换回父窗口

    driver.switchTo().window(parentWindow);
    

    【讨论】:

    • 哪个部分不工作。显示您的一些代码将帮助我们更好地帮助您。切换到新的窗口句柄后,所有操作都将在该窗口上执行。它应该可以工作。
    • 我记得有这个问题并在 IRC 中的 #selenium 上提问。什么是有趣的尝试是向我指出的东西。我编辑了代码以便清楚地显示,但您必须保证在循环窗口句柄时您实际上并没有切换到当前句柄。
    • 终于成功了,先生。我使用了我在回答中提到的一些代码。请看看它,并给我你的反馈先生。谢谢..!! @SpartanElite
    【解决方案3】:

    我终于找到了答案, 我用下面的方法切换到新窗口,

    public String switchwindow(String object, String data){
            try {
    
            String winHandleBefore = driver.getWindowHandle();
    
            for(String winHandle : driver.getWindowHandles()){
                driver.switchTo().window(winHandle);
            }
            }catch(Exception e){
            return Constants.KEYWORD_FAIL+ "Unable to Switch Window" + e.getMessage();
            }
            return Constants.KEYWORD_PASS;
            }
    

    要移动到父窗口,我使用了以下代码,

     public String switchwindowback(String object, String data){
                try {
                    String winHandleBefore = driver.getWindowHandle();
                    driver.close(); 
                    //Switch back to original browser (first window)
                    driver.switchTo().window(winHandleBefore);
                    //continue with original browser (first window)
                }catch(Exception e){
                return Constants.KEYWORD_FAIL+ "Unable to Switch to main window" + e.getMessage();
                }
                return Constants.KEYWORD_PASS;
                }
    

    【讨论】:

    • 我建议只切换到不是当前窗口的窗口。即:将 withHandleBefore 与 withHandle 进行比较。否则,您将不必要地切换所有窗口。
    【解决方案4】:

    要在窗口之间切换,我们有方法。

    driver.switchTo().window("window name") 
    

    要获得不同的窗口句柄,我们有方法。

    driver.getWindowHandles()
    

    例子:

        File file = new File("G:\\Selenium\\All_Jars\\chromedriver.exe");
        System.setProperty("webdriver.chrome.driver",file.getAbsolutePath() );
        driver = new ChromeDriver();
    
        //Maximize the window
        driver.manage().window().maximize();
    
        driver.get("http://www.rediff.com/");
    
        //Get all window handles
        Set<String> allHandles = driver.getWindowHandles();
    
        //count the handles Here count is=2
        System.out.println("Count of windows:"+allHandles.size());      
    
        //Get current handle or default handle
        String currentWindowHandle = allHandles.iterator().next();
        System.out.println("currentWindow Handle"+currentWindowHandle);
    
        //Remove first/default Handle
        allHandles.remove(allHandles.iterator().next());
    
        //get the last Window Handle
        String lastHandle = allHandles.iterator().next();
        System.out.println("last window handle"+lastHandle);
    
        //switch to second/last window, because we know there are only two windows 1-parent window 2-other window(ad window)
    driver.switchTo().window(lastHandle);
        System.out.println(driver.getTitle());
        driver.findElement(By.tagName("body")).click();
    

    【讨论】:

      【解决方案5】:
            Set <String> set = driver.getWindowHandles();
            Iterator<String> it = set.iterator();
            String parentWindowId = it.next();
            String childWindowId = it.next();
            System.out.println(set);
            driver.switchTo().window(childWindowId);
      

      【讨论】:

        【解决方案6】:
            // fetch all windows before clicking on new window link.
            Set<String> windowHandles = driver.getWindowHandles();
            // Click on link to open new window
            driver.findElement(By.tagName("a")).click();  // link to open new window
        
            Set<String> updatedWindowHandles = driver.getWindowHandles();
            updatedWindowHandles.removeAll(windowHandles);
            for (String window: updatedWindowHandles) {
                driver.switchTo().window(window);
            }
        

        【讨论】:

          【解决方案7】:
          //to get the current/parent window
          
          String parentWindowContact = driver.getWindowHandle();
          
          //to switch to the new window from current/parent window
          
          Set<String> handleswindow =driver.getWindowHandles();
          
          for(String windowHandle : handleswindow)
          
          {
          
             driver .switch To().window(windowHandle);
          
          }
          
          //to close the new window
          
          driver.close();
          
          //to switch back to the parent window
          
          driver.switchTo().window(parentWindowContact);
                    o switch back to the parent window
          
          driver.switchTo().window(parentWindowContact);
          

          【讨论】:

            【解决方案8】:

            这是使用索引和标题切换窗口的最佳方法。您可以添加基类并经常使用它。

            public  void switchToWindow(String windowTitle) {
                Set<String> windows = driver.getWindowHandles();
                for (String window : windows) {
                    driver.switchTo().window(window);
                    if (driver.getTitle().contains(windowTitle)) {
                        return;
                    }
                }
            }
            
            
            
            
              public void switchToWindow(int index) {
                Set<String> windows = driver.getWindowHandles();
                int totalWin= windows.size();
                String winTitle = null;
                for(int i=0;i<totalWin;i++) {
                    if(i==index) {
                    winTitle = windows.toArray()[i].toString();
                }
                }
                driver.switchTo().window(winTitle);
                System.out.println(winTitle);
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2015-02-20
              • 1970-01-01
              • 2017-05-13
              • 2013-05-23
              • 2020-11-28
              • 2014-10-20
              • 2018-08-19
              相关资源
              最近更新 更多