解决selenium使用chrome下载文件(如pdf)时,反而打开浏览器的预览界面

文章目录

解决方法

在初始化浏览器的时候,添加以下配置即可:

py 复制代码
    option = webdriver.ChromeOptions()
    prefs = {
        "profile.managed_default_content_settings.images": 2,  # 禁止加载图片
        # 'permissions.default.stylesheet': 2,  # 禁止加载css
        # ====== 配置下载 =====
        'profile.default_content_settings.popups': 0,  # 取消下载确认弹窗
        # 默认下载路径
        'download.default_directory': r"C:\Users\User4\Downloads", # 这个是自定义的下载路径
        "profile.default_content_setting_values.automatic_downloads": 1,  # 允许多文件下载
        "download.prompt_for_download": False,  # To auto download the file
        "download.directory_upgrade": True,
        "plugins.always_open_pdf_externally": True
    }
    option.add_experimental_option("prefs", prefs)
    browser = webdriver.Chrome(options=option)

完整的配置

使用如下程序初始化,可以避免很多问题:

py 复制代码
from selenium import webdriver
def get_browser():
    option = webdriver.ChromeOptions()
    option.add_argument('--disable-gpu')
    option.add_argument('lang=zh_CN.UTF-8')
    # option.add_argument('headless')  # 无界面
    prefs = {
        "profile.managed_default_content_settings.images": 2,  # 禁止加载图片
        # 'permissions.default.stylesheet': 2,  # 禁止加载css
        # ====== 配置下载 =====
        'profile.default_content_settings.popups': 0,  # 取消下载确认弹窗
        # 默认下载路径
        'download.default_directory': r"C:\Users\User4\Downloads",
        "profile.default_content_setting_values.automatic_downloads": 1,  # 允许多文件下载
        "download.prompt_for_download": False,  # To auto download the file
        "download.directory_upgrade": True,
        "plugins.always_open_pdf_externally": True
    }
    option.add_experimental_option("prefs", prefs)
    browser = webdriver.Chrome(options=option)
    browser.implicitly_wait(10)  # 等待元素最多10s
    browser.set_page_load_timeout(10)  # 页面10秒后强制中断加载
    return browser

在需要下载文件时,只需要直接browser.get(网络文件URL)即可直接下载文件到配置的"C:\Users\User4\Downloads"路径下:

py 复制代码
    browser = get_browser()
	browser.get("http://xxxx/xxx.pdf") # 这里会直接下载
相关推荐
我的xiaodoujiao3 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 47--设置Selenium以无头模式运行代码
python·学习·selenium·测试工具·pytest
不会代码的小测试16 小时前
UI自动化-POM封装
开发语言·python·selenium·自动化
林深现海18 小时前
Jetson Orin nano/nx刷机后无法打开chrome/firefox浏览器
前端·chrome·firefox
开开心心就好19 小时前
发票合并打印工具,多页布局设置实时预览
linux·运维·服务器·windows·pdf·harmonyos·1024程序员节
软件工程小施同学21 小时前
区块链论文速读 CCF A--VLDB 2025 (1) 附pdf下载
pdf·区块链
0思必得01 天前
[Web自动化] Selenium获取元素的子元素
前端·爬虫·selenium·自动化·web自动化
John_ToDebug1 天前
引擎深处的漫游者:构建浏览器JavaScript引擎的哲学与技艺
javascript·chrome·js
@zulnger1 天前
selenium 自动化测试工具实战项目(窗口切换)
selenium·测试工具·自动化
senijusene1 天前
Linux软件编程: Linux 操作系统基础与shell脚本
linux·运维·chrome
0思必得02 天前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化