frameset 不用切,frame 需要層層切
frame 標籤有 frameset、frame、iframe 三種,frameset 跟其他普通標籤沒有區別,不會影響到正常的定位,而 frame 與 iframe對selenium 定位而言是一樣的,selenium 有一組方法對 frame 進行操作
1、怎麼切到 frame 中 (switch_to.frame())
selenium 提供了 switch_to.frame() 方法來切換 frame
switch_to.frame(reference)
注意:switch_to_frame(),很多人在這樣寫的時候會發現,這句話被劃上了刪除線,原因是這個方法已經out了,之後很有可能會不支持,建議的寫法是switch_to.frame()
reference 是傳入的參數,用來定位 frame,可以傳入 id、name、index、 以及 selenium 的WebElement 對象
案例:有如下的html文件
<html>
<head>
<title>Freme_test</title>
</head>
<body>
<div>
<iframe id="search" src="http://www.sogou.com" width="800" height="500">
</div>
</body>
</html>
在Frame.html 文件中定位搜狗頁面,進行搜索操作
from selenium import webdriver
d=webdriver.Firefox()
#設置網頁文件路徑,r 代表路徑轉義
#file_path=r'C:\Users\Administrator\Desktop\aa.html'
file_path='file:///C:/Users/Administrator/Desktop/aa.html'
d.get(file_path)
#切換到 frame 頁面內
d.switch_to.frame("search")
#driver.switch_to.frame(0) # 1.用frame的index來定位,第一個是0
# driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) # 用WebElement對象定位
#定位到搜索框按鈕輸入關鍵詞
d.find_element_by_css_selector("#query").send_keys("python")
d.find_element_by_css_selector("#stb").click()
d.quit()
通常採用id和name就能夠解決絕大多數問題。但有時候frame並無這兩項屬性,則可以用index和WebElement來定位:
index從0開始,傳入整型參數即判定爲用index定位,傳入str參數則判定爲用id/name定位
WebElement對象,即用find_element系列方法所取得的對象,我們可以用tag_name、xpath等來定位frame對象
2、從 frame 中切回主文檔(switch_to.default_content())
切到 frame 中之後,我們便不能操作主文檔的元素,這時如果想操作主文檔內容,則需切回主文檔
driver.switch_to.default_content
3、嵌套 frame 的操作(switch_to.parent_frame())
有時候會遇到嵌套 的 frame,如下:
<html>
<iframe id="frame1">
<iframe id="frame2" / >
</iframe>
</html>
(1)從主文檔切到 frame2,一層層切進去
driver.switch_to.frame("frame1") driver.switch_to.frame("frame2")
(2)從 frame2 在切回到 frame1 ,這裏 selenium 給我們提供了一個方法能夠從 子frame 切回到 父frame,而不用我們切回主文檔在切進來
driver.switch_to.parent_frame() # 如果當前已是主文檔,則無效果
有了parent_frame() 這個相當於後退的方法,我們可以隨意切換不同的 frame,隨意的跳來跳去了
所以只要善用一下三個方法,遇到 frame 分分鐘搞定