簡體   English   中英

在Chrome中使用Selenium和Python點擊“下載”按鈕並下載PDF

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM