簡體   English   中英

Selenium Webdriver:如何使用 Python 下載 PDF 文件?

[英]Selenium Webdriver: How to Download a PDF File with Python?

我正在使用 selenium webdriver 自動下載多個 PDF 文件。 我得到了 PDF 預覽窗口(見下文),現在我想下載該文件。 如何使用 Google Chrome 作為瀏覽器完成此操作?

對話框

試試這個代碼,它對我有用。

options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {
"download.default_directory": "C:/Users/XXXX/Desktop", #Change default directory for downloads
"download.prompt_for_download": False, #To auto download the file
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True #It will not show PDF directly in chrome
})
self.driver = webdriver.Chrome(options=options

您可以使用 selenium 從網絡下載 pdf( Embeded pdfNormal pdf )。

from selenium import webdriver

download_dir = "C:\\Users\\omprakashpk\\Documents" # for linux/*nix, download_dir="/usr/Public"
options = webdriver.ChromeOptions()

profile = {"plugins.plugins_list": [{"enabled": False, "name": "Chrome PDF Viewer"}], # Disable Chrome's PDF Viewer
               "download.default_directory": download_dir , "download.extensions_to_open": "applications/pdf"}
options.add_experimental_option("prefs", profile)
driver = webdriver.Chrome('C:\\chromedriver\\chromedriver_2_32.exe', chrome_options=options)  # Optional argument, if not specified will search path.

driver.get(`pdf_url`)

它將下載pdf並將其保存在指定的目錄中。 根據您的方便更改download_dir位置和chrome driver location

您可以從這里下載 chrome 驅動程序。

希望能幫助到你!

我做到了並且有效,不要問我如何:)

options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {
#"download.default_directory": "C:/Users/517/Download", #Change default directory for downloads
#"download.prompt_for_download": False, #To auto download the file
#"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True #It will not show PDF directly in chrome 
})
driver = webdriver.Chrome(options=options)

我在 Stackoverflow 的某個地方找到了這段代碼,它為我服務,根本不需要使用 selenium。

import urllib.request

response = urllib.request.urlopen(URL)    
file = open("FILENAME.pdf", 'wb')
file.write(response.read())
file.close()

在我的情況下,它無需任何代碼修改即可工作,只需要禁用 Chrome pdf 查看器

以下是禁用它的步驟

  1. 進入 Chrome 設置
  2. 滾動到底部點擊高級
  3. 在隱私和安全下 - 單擊“站點設置”
  4. 滾動到 PDF 文檔
  5. 啟用“下載 PDF 文件而不是在 Chrome 中自動打開它們”

有什么辦法可以生成pdf預覽頁面的下載按鈕的xpath或通過配置禁用chrome pdf查看器嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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