Selenium webdriver selecting new window c#

前端 未结 6 1195
清歌不尽
清歌不尽 2020-12-15 07:01

Trying to write some test cases using selenium webdriver in c# and have a scenario which i\'m unsure of how to resolve

user scenario is searching a table for a patie

6条回答
  •  旧巷少年郎
    2020-12-15 07:47

    I've got some code you might like. The quickest solution is to use Popup Finder, but I've made my own method as well. I would never rely on the order the Window Handles are in to select the appropriate window. Popup Window Finder:

    PopupWindowFinder finder = new PopupWindowFinder(driver);
    driver.SwitchTo().Window(newWin); 
    

    My Custom method. Basically you pass it the element you want to click, your webdriver, and optionally the time to wait before searching after you click the element.

    It takes all of your current handles and makes a list. It uses that list to eliminate the previously existing windows from accidentally getting switched to. Then it clicks the element that launches the new window. There should always be some sort of a delay after the click, as nothing happens instantly. And then it makes a new list and compares that against the old one until it finds a new window or the loop expires. If it fails to find a new window it returns null, so if you have an iffy webelement that doesn't always work, you can do a null check to see if the switch worked.

    public static string ClickAndSwitchWindow(IWebElement elementToBeClicked,
    IWebDriver driver, int timer = 2000)
            {
                System.Collections.Generic.List previousHandles = new 
    System.Collections.Generic.List();
                System.Collections.Generic.List currentHandles = new 
    System.Collections.Generic.List();
                previousHandles.AddRange(driver.WindowHandles);
                elementToBeClicked.Click();
    
                Thread.Sleep(timer);
                for (int i = 0; i < 20; i++)
                {
                    currentHandles.Clear();
                    currentHandles.AddRange(driver.WindowHandles);
                    foreach (string s in previousHandles)
                    {
                        currentHandles.RemoveAll(p => p == s);
                    }
                    if (currentHandles.Count == 1)
                     {
                        driver.SwitchTo().Window(currentHandles[0]);
                        Thread.Sleep(100);
                        return currentHandles[0];
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }
                }
                return null;
            }
    

提交回复
热议问题