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

使用Python的Selenium操作Chrome无法下载PDF的问题排查

解决Selenium点击PDF图标后无法下载的问题

问题分析

核心问题包括三点:

  • 点击PDF图标后会打开新标签页,但原代码仍在初始页面操作,导致找不到open-button
  • 依赖time.sleep的等待方式不稳定,元素可能未加载完成就执行点击
  • Chrome的PDF偏好设置未完全生效,未能直接触发下载而是打开了预览页

修正后的代码及说明

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

# 配置Chrome选项,强制PDF直接下载
options = webdriver.ChromeOptions()
prefs = {
    "download.default_directory": "C:\\your_download_path",  # 替换为你的实际下载路径
    "plugins.always_open_pdf_externally": True,
    "download.directory_upgrade": True,
    "plugins.plugins_disabled": ["Chrome PDF Viewer"],  # 禁用内置PDF查看器
    "download.prompt_for_download": False  # 取消下载提示弹窗
}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=options)  # 新版本Selenium无需手动指定executable_path

try:
    driver.get('https://ieeexplore.ieee.org/xpl/conhome/10067248/proceeding?isnumber=10067251&sortType=vol-only-seq&rowsPerPage=75&pageNumber=1')
    
    # 处理Cookie弹窗,用显式等待替代固定sleep
    cookie_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, 'cc-btn'))
    )
    cookie_button.click()
    
    # 等待第一个PDF图标加载完成并点击
    first_pdf_btn = WebDriverWait(driver, 15).until(
        EC.element_to_be_clickable((By.XPATH, "//a[@aria-label='PDF']"))
    )
    first_pdf_btn.click()
    
    # 切换到新打开的PDF预览标签页
    driver.switch_to.window(driver.window_handles[1])
    
    # 等待Open按钮加载完成并点击
    open_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, 'open-button'))
    )
    open_button.click()
    
    # 等待下载完成(可根据文件大小调整等待时间)
    time.sleep(10)
    
finally:
    # 关闭浏览器
    driver.quit()

关键修改点

  • 禁用内置PDF查看器:新增plugins.plugins_disabled配置,强制浏览器直接下载PDF,跳过预览环节
  • 标签页切换:点击PDF链接后会打开新标签,必须通过driver.switch_to.window切换到新窗口,才能定位到open-button
  • 显式等待替代固定sleep:用WebDriverWait确保元素加载完成后再执行操作,避免因页面加载慢导致的元素找不到问题
  • 优化下载配置:新增download.prompt_for_download取消下载确认弹窗,自动完成下载流程

额外提示

  • 确保Chrome浏览器与ChromeDriver版本匹配,避免兼容性问题
  • 若仍无法下载,检查IEEE网站是否需要登录获取PDF资源,必要时需先完成登录操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:42:43