IWebDriver.SwitchTo() frame 和 Window 的用法
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"; }