You need to enable JavaScript to run this app. 如何使用Selenium将iframe内嵌JSP页面下载为PDF格式文件
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Selenium将iframe内嵌JSP页面下载为PDF格式文件

Selenium提取iframe内嵌JSP页面为PDF的实现方案

前置配置:预设浏览器PDF下载行为

为了避免浏览器触发PDF保存弹窗、直接在内置查看器打开文件,需要提前给Chrome配置默认下载规则,所有PDF请求会直接保存到指定本地路径:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os

# 自定义PDF输出目录
output_dir = os.path.abspath("./pdf_result")
os.makedirs(output_dir, exist_ok=True)

chrome_options = Options()
chrome_options.add_experimental_option(
    "prefs",
    {
        "download.default_directory": output_dir,
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        # 核心配置:PDF文件不调用内置查看器,直接走下载流程
        "plugins.always_open_pdf_externally": True
    }
)
driver = webdriver.Chrome(options=chrome_options)

第一步:切换到目标iframe上下文

Selenium默认只能操作主文档内的元素,要读取或操作iframe内嵌的JSP页面,必须先把驱动上下文切换到iframe内部。结合你提供的iframe结构,直接通过id定位即可:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待iframe完全加载,最多等待10秒
wait = WebDriverWait(driver, 10)
wait.until(
    EC.frame_to_be_available_and_switch_to_it((By.ID, "miBody"))
)

第二步:按场景触发PDF导出

根据JSP页面本身的功能不同,可选择两种导出方式:

  • 如果iframe内的JSP页面自带「导出PDF」「打印」按钮,完成上下文切换后,直接定位按钮元素点击即可,浏览器会按照之前配置的规则自动将生成的PDF保存到指定目录
  • 如果JSP页面没有现成的导出按钮,可直接调用Chrome DevTools协议的页面打印能力,将当前iframe内的完整内容导出为PDF,不需要额外依赖第三方库:
import base64

# 调用CDP接口生成PDF文件
pdf_response = driver.execute_cdp_cmd("Page.printToPDF", {
    "printBackground": True,
    "preferCSSPageSize": True
})
# 将返回的Base64格式内容写入本地PDF文件
pdf_path = os.path.join(output_dir, "jsp_page_output.pdf")
with open(pdf_path, "wb") as f:
    f.write(base64.b64decode(pdf_response["data"]))

操作注意事项

  • 在iframe上下文完成所有操作后,如果需要操作外层主页面的元素,必须调用driver.switch_to.default_content()切回主文档上下文,否则会抛出元素找不到的异常
  • 如果导出的PDF存在背景样式丢失、排版错乱问题,可在Page.printToPDF的参数中调整纸张大小、边距配置,匹配原JSP页面的排版规则
  • 不要在未切换iframe的状态下直接查找iframe内部的元素,Selenium的上下文隔离机制会直接阻断跨上下文的元素查找

内容的提问来源于stack exchange,提问作者dazai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.31 07:54:02