[英]Using Selenium with Python in Chrome to click “download” button and download PDF
我正在尝试从以下 url,https://sec.report/Document/00001670/254-20 下载 PDF
html 中嵌入了一个下载按钮。 我正在使用以下代码单击按钮并将下载发送到我的路径中定义的桌面。 程序运行没有任何错误,但 PDF 没有出现在桌面上。 我尝试将位置更改为不同的位置,即下载。 我还切换了 google chrome 中的首选项以下载 PDF 文件,而不是在 Chrome 中自动打开它们。 有任何想法吗?
from selenium import webdriver
download_dir = "C:\\Users\\andrewlittle\\Desktop"
options = webdriver.ChromeOptions()
profile = {"plugins.plugins_list": [{"enabled": False, "name": "Chrome PDF Viewer"}],
"download.default_directory": download_dir , "download.extensions_to_open": "applications/pdf"}
options.add_experimental_option("prefs", profile)
chromedriver_path = os.getcwd() + '/chromedriver'
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://sec.report/Document/0001670254-20-001152/document_1.pdf')
driver.close()
提前致谢!
请参阅下面的答案:
import time
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
download_dir = "/Users/test/Documents/"
options = Options()
options.add_experimental_option('prefs', {
"download.default_directory": download_dir,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True
}
)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://sec.report/Document/0001670254-20-001152/document_1.pdf')
time.sleep(3)
driver.quit()
我把 time.sleep 放在了一些安全性上,以防文件需要更长的时间来下载。 但是,这不是必需的。
我还为 Selenium 使用了更新的服务和选项对象。
代码的关键是使用,
"download.default_directory": download_dir,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True
这些允许 Chrome 在不提示您选择的目录的情况下下载 PDF。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.