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

Chrome Selenium下载文件显示完成但无法找到或打开求助

Selenium操控Chrome下载异常排查与解决

问题描述

使用Selenium操控Chrome时出现下载异常:

  • 浏览器下载面板显示文件已完成,但无法点击文件链接或打开所在文件夹
  • 指定下载路径及系统其他位置均找不到该文件
  • Chrome v121版本下功能正常,当前环境:
    • Chromedriver 131.0.6778.69
    • Chrome 131.0.6778.86
    • Selenium 4.26.1
    • Windows 11系统
  • 手动在Selenium启动的Chrome窗口中操作也无法正常下载,但常规启动Chrome无此问题
  • 已通过ChromeOptions配置并执行CDP命令Page.setDownloadBehavior指定下载路径,日志显示命令执行成功,但无文件生成

相关配置与日志

配置代码

elif os.environ['WEBDRIVER'].lower()=='chrome':
  options = webdriver.ChromeOptions()
  options.add_argument('--no-sandbox')
  options.add_argument('--disable-gpu')
  options.add_argument('--log-level=3')
  options.add_argument('--default-shm-size=32m')
  options.add_argument('--disable-translate')
  options.add_argument('--disable-extensions')
  options.add_argument("--disable-search-engine-choice-screen")   #from v127
  options.add_argument("--proxy-server='direct://'")
  options.add_argument("--proxy-bypass-list=*")
  options.set_capability('acceptInsecureCerts', True)
  s = ChromeService(log_output="./chromedriver.log", service_args=['--append-log', '--readable-timestamp', '--log-level=DEBUG'])
  driver = webdriver.Chrome(service=s, options=options)
  if downloadpath:
    params = {'behavior': 'allow', 'downloadPath': downloadpath}
    driver.execute_cdp_cmd('Page.setDownloadBehavior', params)
    log.error(f"downloadpath:{downloadpath}")

Chromedriver.log关键内容

[11-22-2024 15:50:50.149][INFO]: [8910dee67519a9b5866d52afebfbf3c1] COMMAND ExecuteCDP {
   "cmd": "Page.setDownloadBehavior",
   "params": {
      "behavior": "allow",
      "downloadPath": "C:\\dist\\work\\remote-eseal-fullstack-test"
   }
}
[11-22-2024 15:50:50.149][INFO]: Waiting for pending navigations...
[11-22-2024 15:50:50.149][DEBUG]: DevTools WebSocket Command: Runtime.evaluate (id=11) (session_id=61E316801F90E64FADC42C44338093B5) A4E93A55626FB44C23A9F9249BA7239F {
   "expression": "1"
}
[11-22-2024 15:50:50.150][DEBUG]: DevTools WebSocket Response: Runtime.evaluate (id=11) (session_id=61E316801F90E64FADC42C44338093B5) A4E93A55626FB44C23A9F9249BA7239F {
   "result": {
      "description": "1",
      "type": "number",
      "value": 1
   }
}
[11-22-2024 15:50:50.150][INFO]: Done waiting for pending navigations. Status: ok
[11-22-2024 15:50:50.150][DEBUG]: DevTools WebSocket Command: Page.setDownloadBehavior (id=12) (session_id=61E316801F90E64FADC42C44338093B5) A4E93A55626FB44C23A9F9249BA7239F {
   "behavior": "allow",
   "downloadPath": "C:\\dist\\work\\remote-eseal-fullstack-test"
}
:
<down to last entry mentioning the pdf>
:
[11-22-2024 15:50:55.321][DEBUG]: DevTools WebSocket Event: Page.windowOpen (session_id=D072486C5680E0BC8FE19F80C8467224) 9A5B198EA74FBCFC94BF48195F3EB3B8 {
   "url": "https://**********/remote-eseal-demo-web/signed/buypass-finse-2022_signed.pdf",
   "userGesture": true,
   "windowFeatures": [ "menubar", "toolbar", "status", "scrollbars", "resizable", "noopener" ],
   "windowName": "_blank"
}

下载面板截图

下载面板显示文件但无法操作

解决方案

1. 替换CDP命令为Selenium原生下载配置

Chrome 115+版本后,Selenium提供了更稳定的原生下载目录设置方式,替代旧的Page.setDownloadBehavior:

import os
from selenium.webdriver import Chrome, ChromeOptions, ChromeService

# 提前创建下载目录
if not os.path.exists(downloadpath):
    os.makedirs(downloadpath)

# 配置下载偏好
prefs = {
    "download.default_directory": downloadpath,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "plugins.always_open_pdf_externally": True  # 强制PDF下载而非在浏览器中打开
}
options.add_experimental_option("prefs", prefs)

# 初始化driver
driver = Chrome(service=s, options=options)

2. 处理新窗口打开的下载链接

从日志看,下载链接通过_blank新窗口打开,需切换窗口处理:

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

# 记录主窗口句柄
main_window = driver.current_window_handle

# 触发下载
download_btn = driver.find_element(By.CSS_SELECTOR, "your-download-selector")
download_btn.click()

# 等待新窗口出现并切换
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
for handle in driver.window_handles:
    if handle != main_window:
        driver.switch_to.window(handle)
        break

# 关闭新窗口并切回主窗口
driver.close()
driver.switch_to.window(main_window)

3. 适配Chrome 130+版本的CDP命令

若仍需使用CDP命令,需添加eventsEnabled参数,且确保在页面加载前执行:

params = {
    "behavior": "allow",
    "downloadPath": downloadpath,
    "eventsEnabled": True
}
driver.execute_cdp_cmd('Page.setDownloadBehavior', params)

4. 补充权限相关参数

Windows环境下添加额外参数,避免权限限制:

options.add_argument('--disable-web-security')
options.add_argument('--allow-running-insecure-content')
options.add_argument('--disable-features=VizDisplayCompositor')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:49:51