首页 > 解决方案 > 如何在 python 中使用 selenium 下载文件?

问题描述

我想使用 python 下载文件,但我做不到。我尝试寻找方法,但我找不到任何相关资源。

这是我的代码:

from selenium import webdriver
driver = webdriver.Chrome('/home/user/Downloads/chromedriver')

#The below link is a pdf file and not an HTML file. I want to download this file directly.

driver.get("https://authlink-files-storage.ams3.digitaloceanspaces.com/authlink/transfered_certificates_related_docs/supporting_docs_17_2020_07_24_06_25_764ffb965d1b4ae287a0d3cc01c8dd03")

现在我想下载这个文件,但我做不到。

标签: python-3.xseleniumselenium-chromedriver

解决方案


如果直接下载不起作用,您始终可以使用打印功能解决问题:

  1. 需要使用chrome选项--kiosk-printing,一旦打开打印对话框,它将自动单击打印按钮

    选项 = webdriver.ChromeOptions()

    options.add_argument("--kiosk-printing")

  2. 将 chrome 首选项定义为 JSON 字符串

prefs = {"savefile.default_directory": "your destination path", "printing.default_destination_selection_rules": {"kind": "local", "idPattern": ".*", "namePattern": "Save as PDF"}}

在上述首选项中,默认目录将用于将您的 pdf 保存在所需位置。第二个首选项将自动从打印对话框中选择“另存为 pdf”选项

  1. 添加 pref 作为实验选项

    options.add_experimental_option(“首选项”,首选项)

  2. 使用 chrome 选项和首选项定义驱动程序

    驱动程序 = webdriver.Chrome(chrome_options=options)

  3. 在 url 中打开 pdf 后,您可以使用 javascript 打开打印对话框

    driver.execute_script("window.print()")

您的 pdf 将以相同的标题保存在目标路径中


推荐阅读