Frame切換

Frame標(biāo)簽有Frameset、Frame和IFrame 3種,F(xiàn)rameset跟其他普通標(biāo)簽沒有區(qū)別,不會(huì)影響到正常的定位。在頁面中經(jīng)常能看到Frame或IFrame(Frame是整個(gè)頁面的框架,IFrame是內(nèi)嵌的框架),由于WebDriver定位元素時(shí)只能在一個(gè)頁面上定位,所以對于IFrame這樣的情況,WebDriver是無法直接定位到元素的。Selenium中有對應(yīng)的方法對Frame進(jìn)行操作。

WebDriver提供了switch_to.frame()方法來切換Frame,格式如下:

switch_to.frame(定位元素)

1.切換IFrame

案例描述如下:·外部頁面有個(gè)指向baidu的鏈接;·內(nèi)嵌的頁面是通過IFrame實(shí)現(xiàn)的,嵌套的是Bing首頁。

iframe.html頁面的實(shí)現(xiàn)代碼如下:

<!DOCTYPE html>

<html lang="en">

<head>

? ? <meta charset="UTF-8">

? ? <title>iframe-HTML</title>

</head>

<body>

<div class="alert" align="center">The link

? ? <a class="alert-link" >baidu</a>

</div>

<div class="row-fluid">

? ? <div class="span-ifram" align="center">

? ? ? ? <h4 align="center">iframe</h4>

? ? ? ? <iframe id = "iname" name="nf" src="https://cn.bing.com" width="800" height="600"></iframe>

? ? </div>

</div>

</body>

</html>

單擊Bing搜索頁的搜索框完成關(guān)鍵字的搜索。iframe.html代碼中IFrame標(biāo)簽的id等于"iname"。實(shí)現(xiàn)代碼如下:

from selenium import webdriver

import time

driver = webdriver.Chrome()

driver.get("D:\\protect\\python\\selenuim\\module\\iframe.html")

driver.switch_to.frame("iname")#切換窗體

time.sleep(2)

driver.find_element_by_xpath("http://*[@id='sb_form_q']").send_keys("selenium")

driver.find_element_by_xpath("http://*[@id='sb_form_go']").click()

time.sleep(2)

driver.quit()

2.切換到主窗體

當(dāng)切換到子窗體Frame中之后,便不能繼續(xù)操作主窗體中的元素了,這時(shí)如果要操作主窗體中的元素,則需切換回主窗體。

基于上面的用例,當(dāng)對Bing搜索頁完成操作后,如想單擊外部的baidu鏈接,則需要切換到主窗體。切換到主窗體的方法是driver.switch_to.default_content()。實(shí)現(xiàn)代碼如下:

driver.get("D:\\protect\\python\\selenuim\\module\\iframe.html")

driver.switch_to.frame("iname")#切換窗體

time.sleep(2)

driver.find_element_by_xpath("http://*[@id='sb_form_q']").send_keys("selenium")

driver.find_element_by_xpath("http://*[@id='sb_form_go']").click()

driver.switch_to.default_content()#跳到最外層

driver.find_element_by_xpath("/html/body/div[1]/a").click()

time.sleep(2)

driver.quit()

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容