python-3.x - 如何在 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")
现在我想下载这个文件,但我做不到。
解决方案
如果直接下载不起作用,您始终可以使用打印功能解决问题:
需要使用chrome选项--kiosk-printing,一旦打开打印对话框,它将自动单击打印按钮
选项 = webdriver.ChromeOptions()
options.add_argument("--kiosk-printing")
将 chrome 首选项定义为 JSON 字符串
prefs = {"savefile.default_directory": "your destination path", "printing.default_destination_selection_rules": {"kind": "local", "idPattern": ".*", "namePattern": "Save as PDF"}}
在上述首选项中,默认目录将用于将您的 pdf 保存在所需位置。第二个首选项将自动从打印对话框中选择“另存为 pdf”选项
添加 pref 作为实验选项
options.add_experimental_option(“首选项”,首选项)
使用 chrome 选项和首选项定义驱动程序
驱动程序 = webdriver.Chrome(chrome_options=options)
在 url 中打开 pdf 后,您可以使用 javascript 打开打印对话框
driver.execute_script("window.print()")
您的 pdf 将以相同的标题保存在目标路径中
推荐阅读
- python - 为什么第二个循环从未执行?
- python-2.7 - Python exec_command 抛出未知命令:`ls'
- amazon-web-services - mbedtls 熵生成 (nv_seed)
- mongodb - docker-compose MongoDB 错误:尝试在主机上运行命令“isMaster”时出现网络错误
- f# - 我怎样才能让`printfn“%A”`打印完整的复杂结构?
- javascript - d3:如何在水平方向移动垂直线并支持“暂停”和“继续”移动
- java - 我收到空值错误,因为 java.lang.AssertionError: Lists different at element [0]: != Selenium expected [] but found [Selenium]
- javascript - jQuery('#myModal:visible').length === 0 在 Javascript
- java - 使用 if 语句依次执行这两个代码
- react-native - 如何使用 SeionList 展开和折叠指定部分?