iframe的属性获取

必须先切换到 iframe 内,才能访问内部文档的属性,

python 复制代码
driver.switch_to.frame(iframe_element)  # 切换到 iframe

获取文档标题(document.title

python 复制代码
title = driver.title  # 直接获取当前文档标题
# 或通过 JS
title = driver.execute_script("return document.title")

当前 iframe 内页面的 URL

iframe 内页面的 URL 并不是浏览器地址栏的 URL,而是其自身加载的地址。用driver.current_url获取到是主文档的url,并不是iframe的URL

可以通过以下方式获取:

python 复制代码
current_url_in_iframe = driver.execute_script("return document.location.href")

获取iframe的加载状态

python 复制代码
iframe_ready_state = driver.execute_script("return document.readyState")

获取来源页面 URL

python 复制代码
iframe_referrer = driver.execute_script("return document.referrer")

获取页面性能/几何信息

python 复制代码
# 页面可视区域宽高
viewport_width = driver.execute_script("return window.innerWidth")
viewport_height = driver.execute_script("return window.innerHeight")

# 页面总宽高(含滚动)
page_width = driver.execute_script("return document.body.scrollWidth")
page_height = driver.execute_script("return document.body.scrollHeight")

完整示例:

python 复制代码
# 假设已定位到 iframe 元素
iframe = driver.find_element(By.CSS_SELECTOR, "iframe.layui-layer-iframe")

# 获取 iframe 本身的属性
iframe_src = iframe.get_attribute("src")
iframe_title_attr = iframe.get_attribute("title")

# 切换到 iframe
driver.switch_to.frame(iframe)

# 获取内部文档的标题和 URL(同域下)
inner_title = driver.title
inner_url = driver.execute_script("return document.location.href")

print(f"iframe 元素 src: {iframe_src}")
print(f"iframe 元素 title 属性: {iframe_title_attr}")
print(f"iframe 内部文档标题: {inner_title}")
print(f"iframe 内部文档 URL: {inner_url}")

# 切回主页面
driver.switch_to.default_content()

注意事项

  1. 跨域限制 :如果 iframe 加载的是不同域的页面(如外部网站),出于浏览器安全策略,你将无法通过 driver.execute_script() 访问其内部的 document 属性(会报跨域错误)。这种情况下只能获取 iframe 元素本身的属性(如 srctitle 等)。

  2. 等待加载:在获取内部文档属性前,确保 iframe 已经完全加载,可以使用:

    python 复制代码
    driver.switch_to.frame(iframe_element)
    
    WebDriverWait(driver, 10).until
    (lambda d: d.execute_script("return document.readyState") == "complete")
  3. 切换回主页面:操作完 iframe 后,记得切回默认内容:

    python 复制代码
    driver.switch_to.default_content()
相关推荐
CAD老兵1 天前
一张 HTML 走天下:CAD-Viewer 首创的「离线 CAD 看图」
前端·javascript·github
程序员榴莲1 天前
Python 中的 @property:像访问属性一样调用方法
开发语言·前端·python
sycmancia1 天前
Qt——拖放事件深度剖析
开发语言·qt
坐吃山猪1 天前
【Nanobot】README09_LEVEL4 添加新聊天渠道
开发语言·网络·python·源码·nanobot
shehuiyuelaiyuehao1 天前
算法27,二维前缀和
开发语言·python·算法
IpdataCloud1 天前
企业安全运营中,如何用IP风险识别工具快速发现异常终端?操作指南
开发语言·php
兩尛1 天前
C++多线程,并发
java·开发语言
大师兄66681 天前
HarmonyOS 服务卡片开发之JS 卡片开发
javascript·华为·harmonyos·harmonyos6·formkit
计算机安禾1 天前
【c++面向对象编程】第29篇:定位new(placement new):在指定内存上构造对象
开发语言·c++·算法
计算机安禾1 天前
【c++面向对象编程】第27篇:空类的大小为什么是1?——C++对象标识的秘密
开发语言·c++·算法