Selenium定位不到元素的解決方法—iframe擋住了去路
剛接觸Selenium,在調試過程中發現有些元素定位不到,于是求助了百度,查找到的資料是這么說的:如果需要定位的元素在某個frame里,則單獨通過id/name/xpath是定位不到此元素的。比如,原本想通過WebElement element=driver.FindElement(By.LinkText("XXX"));來定位元素的,但由于該元素在iframe. id="left_frame"這個frame里面,所以需要先定位frame,WebElement element=driver.SwitchTo().Frame("left_frame").FindElement(By.LinkText("XXX"));
此外還有個問題,就是相關的操作是在不同的frame中定位元素的。比如,先在left_frame中定位元素Id=TestFor1,然后在right_frame中定位元素Id=TestFor2。這種情況下,先切到left_frame,driver.SwitchTo().Frame("left_frame");再定位元素TestFor1,driver.FindElement(By.Id("TestFor1"));再切到默認的content,driver.SwitchTo().DefaultContent();再切到right_frame,driver.SwitchTo().Frame("right_frame");再定位元素TestFor2,driver.FindElement(By.Id("TestFor2"));
在實際應用中,該方法能解決元素無法定位的問題,寫了個C#通用接口(不管元素是否在frame里面),如下:
publicIWebElementGetElement(stringstrDefined,boolbFrame.=false) { try { // 如果元素不在frame中,則切到默認的content if(!bFrame) { _webDriver.SwitchTo().DefaultContent(); } IWebElementele=null; stringstrFrame.=m_cc.GetElementFrame(strDefined); // 如果元素在frame里,先切到frame if(null!=strFrame.&&""!=strFrame) { IWebElementFrameEle=GetElement(strFrame,true); _webDriver.SwitchTo().Frame(FrameEle); } stringstrID=m_cc.GetElementID(strDefined); // 如果元素的ID為空,則通過XPath來定位元素 if(""==strID) { stringstrXPath=m_cc.GetElementXPath(strDefined); else=_webDriver.FindElement(By.XPath(strXPath)); } else } } |
版權聲明:本文出自 xiaobaiwdn 的51Testing軟件測試博客:http://www.51testing.com/?367232
原創作品,轉載時請務必以超鏈接形式標明本文原始出處、作者信息和本聲明,否則將追究法律責任。
posted on 2014-01-02 09:31 順其自然EVO 閱讀(3644) 評論(0) 編輯 收藏 所屬分類: selenium and watir webdrivers 自動化測試學習