例如網頁代碼為:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<iframe id= "baidu" name="百度" src="http://www.BAIDU.com" HEIGHT="300" WIDTH="1280"></iframe>
<iframe id= "sougou" name="搜狗" src="https://www.sogou.com/" HEIGHT="300" WIDTH="1280"></iframe>
</body>
</html>
頁面如下:

當我們需要去定位百度搜索框的ID時,如上面的源碼所示,是沒有百度搜索框的ID,因為百度和搜狗頁面是嵌套的鏈接,我們需要切換到百度的域里面,才可以定位到搜索框的ID

from selenium import webdriver
driver = webdriver.Firefox()
driver.switch_to.frame(0) # 1.用frame的index來定位,第一個是0
# driver.switch_to.frame("baidu") # 2.用id來定位
# driver.switch_to.frame("百度") # 3.用name來定位
# driver.switch_to.frame(driver.find_element_by_tag_name("百度")) # 4.用WebElement對象來定位
# driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@id,'baidu')]")) # 5.用xpath定位,傳入WebElement對象
driver.switch_to.frame('baidu) # iframe一層一層的切入
driver.switch_to.parent_frame() # iframe退后操作,一層一層的退回
driver.switch_to.default_content() # 切換到主頁面
注意:
使用driver.switch_to_frame()時,會提示該方法已經過時;
需要使用新的driver.switch_to.frame()方法。
