frame、iframe
相信大部分使用selenium的同学都会遇见一个现象,就是明明可以定位到元素,但是就是无法操作;这个是因为遇到了frame、iframe
这个东西
frame标签有frameset、frame、iframe
三种,
frameset和其他普通标签没有区别,不会影响到定位
它们两个的学名叫做框架,顾名思义,首先你要进去这个框架再进行操作,操作完成再从这个框架离开
selenium就提供了三种方式,来进行frame、iframe
的访问
WebElement
name、id
- 使用索引
话不多说,让我们开始实践
WebElement
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Serviceserve_path = r'D:\Code_Study\driver\chromedriver-win64\chromedriver.exe'
service = Service(serve_path)
browser = webdriver.Chrome(service=service)
browser.get(f'https://the-internet.herokuapp.com/nested_frames')
# WebElement;先找到这个框架元素,在进行切换
frameset = browser.find_element(By.NAME, "frame-top")
# 切换到大的frame
browser.switch_to.frame(frameset)
# 定位上半部分中间的frame,并切换
frame_middle = browser.find_element(By.NAME, "frame-middle")
browser.switch_to.frame(frame_middle)
# 输出里面的内容
print(browser.find_element(By.ID, "content").text) # MIDDLE
name、id
# 如果frama有Id、name属性的话,可以使用该属性;如果不是唯一的话,会默认找第一个
# 先找到上面的frame,再找到中间的
browser.switch_to.frame("frame-top")
browser.switch_to.frame("frame-left")
# # 输出里面的内容
print(browser.find_element(By.TAG_NAME, "body").text) # LEFT
使用索引
frame_top = browser.find_elements(By.TAG_NAME, 'frame')[0]
browser.switch_to.frame(frame_top)
frame_right = browser.find_elements(By.TAG_NAME, 'frame')[2]
browser.switch_to.frame(frame_right)
print(browser.find_element(By.TAG_NAME, "body").text) # RIGHT
注意离开框架
不管你使用上面什么方法,最后需要离开框架,切换回默认内容
switch_to.parent_frame()返回父文档
switch_to.default_content()返回主文档
# 离开框架
# switch_to.default_content()返回主文档
# switch_to.parent_frame()返回父文档frame_top = browser.find_elements(By.TAG_NAME, 'frame')[0]
browser.switch_to.frame(frame_top)
frame_right = browser.find_elements(By.TAG_NAME, 'frame')[2]
browser.switch_to.frame(frame_right)
print(browser.find_element(By.TAG_NAME, "body").text) # RIGHT
# 返回父文档,回到frame_top
# browser.switch_to.parent_frame()
# print(browser.page_source)
"""
<html><head></head><frameset frameborder="1" name="frameset-middle" cols="33%,33%,33%"><frame src="/frame_left" scrolling="no" name="frame-left"><frame src="/frame_middle" scrolling="no" name="frame-middle"><frame src="/frame_right" scrolling="no" name="frame-right" cd_frame_id_="757301613216e105ebb32711cd5c35dd">
</frameset>
</html>
"""# 直接返回主文档
browser.switch_to.default_content()
print(browser.page_source)
"""
<html><head></head><frameset frameborder="1" rows="50%,50%"><frame src="/frame_top" scrolling="no" name="frame-top" cd_frame_id_="a74a433876cf3abadc9fddf601c55829"><frame src="/frame_bottom" scrolling="no" name="frame-bottom"><noframes>Frames are not rendering.</noframes>
</frameset>
</html>
"""
好了,frame的东西到这里就结束了;有疑问的可以评论区讨论