iframe:一個網頁里面嵌套了另一個框架/頁面,即在一個HTML頁面中還內嵌了另外一個HTML頁面,只不過這個內嵌的HTML是放在</frame></iframe>標簽對中。
在python3.8中對應的selenium提供了兩種方法來獲取iframe中的內容:
方式一:driver.switvh_to.frame(frame_reference)
語法:
driver.switch_to.frame(iframe的name屬性或webelement對象或下標)
示例:
driver.switch_to.frame(“login_frame_qq”)#切換到name為login_frame_qq的iframe中
driver.switvh_to.frame(0)#切換到第一個iframe中
driver.switch_to.frame((By.xpath,"//div[@class="ptlogin_wrap"]))
方式二:frame_to_be_available_and_switch_to_it(frame_reference)
在前面的selenium常用操作之等待操作中我們有介紹過,expected_conditons模塊中提供的方法。
此方法會判斷iframe是否可用,並且會自動切換到iframe中。
frame_reference的值與方式一保持一致。
示例:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
WebDriverWait(driver,20).until(EC.frame_to_be_available_and_switch_to_it(iframe_name))
當頁面中iframe中還有iframe時,假如此時我們想進入二級iframe,則需要先進入一級iframe,再進入二級iframe。
#iframeId為一級iframe的id
driver.switch_to_frame("iframeId")
#iframeId下有兩個並列的iframe,但是他們沒有id和name,此時我們可以通過tag_name獲取
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[1])
這樣我們就進入了一級iframeId下的iframe了!
selenium跳出iframe
①從二級iframe跳到一級iframe,即跳到父級:
driver.switchTo().parentFrame();
#或者
driver.switch_to.parent_frame()
②從iframe跳到主窗口
driver.switch_to_default_content()
#或者
driver.switch_to.default_content()
