You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Selenium WebDriver等待PDF页面加载完成的方法求助

问题原因

你之前的代码失效是因为Chrome内置PDF阅读器渲染的界面元素属于浏览器插件的私有渲染内容,不属于当前页面的普通DOM树,常规的元素定位方法无法捕获到这些元素,因此等待ID为icon的元素的逻辑永远不会触发。

解决方案

Chrome/Edge等主流浏览器的内置PDF阅读器均基于PDF.js实现,会在全局暴露PDFViewerApplication对象,我们可以通过执行JavaScript脚本判断该对象的状态,确认PDF是否完全加载完成,修改后的代码如下:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

class Test():
    def __init__(self):
        # 注意路径前加r防止Windows路径转义问题
        self.driver = webdriver.Chrome(executable_path=r"drivers\chromedriver.exe")
        self.wait = WebDriverWait(self.driver, 60)
        self.driver.maximize_window()
        self.driver.get("https://readthedocs.org/projects/selenium-python/downloads/pdf/latest/")
        
        # 核心逻辑:通过JS判断PDF加载状态
        self.wait.until(lambda dr: dr.execute_script("""
            if (window.PDFViewerApplication) {
                // 确认PDF文档对象已生成、总页数已计算完成,代表加载完毕
                return PDFViewerApplication.pdfDocument !== null && PDFViewerApplication.pagesCount > 0;
            }
            return false;
        """))
        
        # 加载完成后输出提示
        print("Page is ready")
        # 如果需要点击下载按钮,直接调用PDF.js内置方法比定位元素更稳定
        # self.driver.execute_script("PDFViewerApplication.download()")

if __name__ == "__main__":
    oTest = Test()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:09:03