在web 应用中经常会出现frame 嵌套的应用。在使用 Selenium 进行 Web 自动化测试时,定位 iframe 可以通过以下几种方式实现:
第一种——通过索引定位:
driver.switch_to.frame(0) # 切换到第一个 iframe
# 在 iframe 中进行操作
driver.switch_to.default_content() # 切换回默认的主页面
第二种——通过名称或 ID 定位:
driver.switch_to.frame("iframe_name") # 通过名称定位
# 在 iframe 中进行操作
driver.switch_to.default_content() # 切换回默认的主页面driver.switch_to.frame("iframe_id") # 通过 ID 定位
# 在 iframe 中进行操作
driver.switch_to.default_content() # 切换回默认的主页面
第三种——通过元素定位:
from selenium.webdriver.common.by import By
# 先定位到父元素
parent_element = driver.find_element(By.XPATH, "父元素定位表达式")
# 再通过父元素找到子 iframe 元素
iframe_element = parent_element.find_element(By.XPATH, "子元素定位表达式")driver.switch_to.frame(iframe_element) # 切换到指定的 iframe
# 在 iframe 中进行操作
driver.switch_to.default_content() # 切换回默认的主页面
实战:
下面的代码中frame.html 里有个id 为f1 的frame,而f1 中又嵌入了id 为f2 的frame,该frame 加载了搜狗的首页。
frame.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-Frame-Options" content="allow">
<title>Document</title>
</head>
<body>
<div >
<h3>frame</h3>
<iframe id="f1" src="inner.html" width="900" height="600"></iframe>
</div>
</body>
</html>
inner.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-Frame-Options" content="allow">
<title>Document</title>
</head>
<body>
<h3>inner</h3>
<iframe id="f2" src="https://www.sogou.com/" width="800" height="400">
</iframe>
</body>
</html>
mian.py
from selenium import webdriver
import os
from time import sleep
def test01():
chrome = webdriver.Chrome()
file_path = 'file:///'+os.path.abspath('./1/html/iframe.html')
chrome.get(file_path)
chrome.switch_to.frame('f1')
chrome.switch_to.frame('f2')
chrome.find_element_by_id('query').send_keys('python')
chrome.find_element_by_id('stb').click()
sleep(5)
if __name__=="__main__":
test01()