webdriver如何定位多層iframe中元素


在 web 應用中經常會出現 iframe 嵌套的應用,假設頁面上有 A、B 兩個 iframe,其中 B 在 A 內,那么定位 B 中的內容則需要先到 A,然后再到 B。

iframe 中實際上是嵌入了另一個頁面,而 webdriver 每次只能在一個頁面識別,因此需要用 switch_to.frame 方法去獲取 iframe 中嵌入的頁面,對那個頁面里的元素進行定位。

常用方法如下:

# 先找到到 iframe1(id = f1)

driver.switch_to_frame("f1")

# 再找到其下面的 iframe2(id =f2)

driver.switch_to_frame("f2")

# 下面就可以正常的操作元素了

driver.find_element_by_id("xx").click()

例:要求定位id="TeacherTxt"

<frame src="" id="index_main" name="main" scrolling="Yes" noresize="noresize">
        <iframe id="Editor1" src="" frameborder="0" scrolling="no" >
              <iframe id="eWebEditor" width="100%" height="100%" scrolling="yes" frameborder="0" src="">
                  <input type="text" id="TeacherTxt" name="Teacher" size="12" maxlength="12" >
            </iframe>
        </iframe>
</iframe>
代碼如下:
driver.switch_to_frame("inden_main")
driver.switch_to_frame("Editor1")
driver.switch_to_frame("eEebEditor")
driver.find_element_by_id("TeacherTxt").send_keys('tester')
 

注:若頁面中只有一個iframe且這個iframe為js加載的,那么只需要switch_to_frame(‘id’)即可

---------------------------------------------------------------------------------------------------------------------------------

有可能嵌套的不是框架,而是窗口,還有針對窗口的方法:switch_to_window 

用法與switch_to_frame 相同: 

driver.switch_to_window("windowName")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM