Selenium 打開新標籤頁獲取元素

原博主鏈接:https://www.cnblogs.com/qixue/p/3928775.html

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";
        }
複製代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章