解决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") # 这里会直接下载
相关推荐
简离1 天前
前端调试实战:基于 chrome://webrtc-internals/ 高效排查WebRTC问题
前端·chrome·webrtc
百事牛科技2 天前
保护文档安全:PDF限制功能详解与实操
windows·pdf
开开心心就好2 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
xixi09242 天前
selenium IDE——command
selenium·测试工具
Ai老司机2 天前
Chrome浏览器驱动(ChromeDriver)官方下载 - 全平台高速镜像站 | chromedrive.cn
前端·chrome
电商API_180079052472 天前
如何将小红书评论数据封装到API实现自动化分析?测试API实战指南
运维·chrome·自动化
~远在太平洋~2 天前
debian系统已安装python3.12却无法执行python命令
chrome·python·debian
阿珊和她的猫2 天前
浏览器跨页签数据共享方案
前端·javascript·vue.js·chrome
xixi09242 天前
selenium IDE安装使用教程
ide·selenium·测试工具