Selenium

IWebDriver.SwitchTo().Frame(IWebElement frame)

如果一个页面是一个html元素, 只有一个head, 一个body, 那么使用IWebDriver.FindElement()查找页面中的任何一个元素都没有问题。但是,由于页面中<frame ... 的使用,使得一个原始的html页面中可以包含多个子html页面, 在这种情况下,使用IWebDrivr.FindElement()查找页面 某个元素,如果元素是属于元素大的html的, 那么没有问题。若该元素是属于某个子的<frame ...下的,获得页面元素会失败的。要想成功,首先要弄清楚该元素所属的frame的, 其次, 将IWebDriver切换到该frame, 然后再使用IWebDriver.FindElement()查找这个元素。

1. 获得页面元素所属于的frame, 拿到它的name属性。

2. 使用IWebDriver.FindElements()获得本页面中所有的frame, 使用ByTagName。

3. 循环遍历所有Frame,查找name属性相符的Frame。

4. 将IWebDriver焦点切换到该Frame, 查找要获得的页面元素。

例如, 我的页面元素如下:

这个页面中, 要想获得id是"testcategory"的span元素, 直接使用IWebDriver.FindElement(By.ID("testcategory"))是没有用的, 找不到这个element。

正确的代码如下:

using Se = OpenQA.Selenium;
using SIE = OpenQA.Selenium.IE;

            SIE.InternetExplorerDriver driver = new SIE.InternetExplorerDriver();
            // all frames
            IList<Se.IWebElement> frames = driver.FindElements(Se.By.TagName("frame"));
            Se.IWebElement controlPanelFrame = null;
            foreach (var frame in frames)
            {
                if (frame.GetAttribute("name") == "ControlPanelFrame")
                {
                    controlPanelFrame = frame;
                    break;
                }
            }

            if (controlPanelFrame != null)
            {
                driver.SwitchTo().Frame(controlPanelFrame);
            }        

            // find the spane by id in frame "ControlPanelFrame"
            Se.IWebElement spanElement = driver.FindElement(Se.By.Id("testcategory"));


IWebDriver.SwitchTo().Window(string windowName)

在页面上点击一个button, 然后打开了一个新的window, 将当前IWebDriver的focus切换到新window,使用IWebDriver.SwitchTo().Window(string windowName)。

例如, 我点击按钮以后弹出一个名字叫做"Content Display"的window, 要切换焦点到新窗口的方法是, 首先,获得新window的window name, 大家不要误以为page tile就是window name 哦, 如果你使用driver.SwitchTo().Window("Content Display")是找不到window name 叫做"Content Display"的窗口的, 其实Window Name 是一长串数字,类似“59790103-4e06-4433-97a9-b6e519a84fd0”。

要正确切换到"Content Display"的方法是:

1. 获得当前所有的WindowHandles。

2. 循环遍历到所有的window, 查找window.title与"Content Display"相符的window返回。

大家明白了吧, 正确的代码:

using Se = OpenQA.Selenium;
using SIE = OpenQA.Selenium.IE;

        public static string GoToWindow(string title, ref SIE.InternetExplorerDriver driver)
        {
            driver.SwitchTo().DefaultContent();

            // get all window handles
            IList<string> handlers = driver.WindowHandles;
            foreach (var winHandler in handlers)
            {
                driver.SwitchTo().Window(winHandler);
                if (driver.Title == title)
                {
                    return "Success";
                }
                else
                {
                    driver.SwitchTo().DefaultContent();
                }
            }

            return "Window Not Found";
        }
原文地址:https://www.cnblogs.com/qixue/p/3928775.html