在进行UI自动化中,会遇到元素在iframe框中,在对其进行定位时需先切换到该iframe中,对iframe定位可以通过iframe元素位置定位,也可以通过索引定位
如下:index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <center> <a href="index1.html">测试</a> </center> <iframe src="index1.html" name="test"> <iframe src="index1.html" name="test2"> </iframe> </iframe> </body> </html>
index1.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <center id="kt"> 测试课堂 </center> </body> </html>
通过元素定位iframe
from selenium import webdriver driver = webdriver.Chrome() driver.maximize_window() driver.get("D:\pycharmwokspace\UITESThtml\index.html") iframe_el = driver.find_element_by_name("test") driver.switch_to.frame(iframe_el) print(driver.find_element_by_id("kt").text) driver.quit()
通过索引定位
from selenium import webdriver driver = webdriver.Chrome() driver.maximize_window() driver.get("D:\pycharmwokspace\UITESThtml\index.html") # iframe_el = driver.find_element_by_name("test") driver.switch_to.frame(0) print(driver.find_element_by_id("kt").text) driver.switch_to.default_content() #切换到最外层 driver.quit()
多层嵌套的实现思路为:先进入第一层,再进入第二层,写法类似