首页 > 解决方案 > 在另一个浏览器页面上打开时如何在python中使用selenium自动下载PDF文件

问题描述

我正在单击带有 selenium 的链接,它正在打开一个带有 PDF 的新浏览器选项卡,我想知道是否有办法下载该 PDF,我不在乎浏览器选项卡是否打开然后开始下载,我想要的是下载那个PDF。

谢谢

标签: pythonselenium

解决方案


你可以使用 pyautogui 和 Options

import pyautogui
from selenium.webdriver.chrome.options import Options

DRIVER_PATH = r'chromedriver.exe'  //chromedriver path
chrome_options = Options()
chrome_options.add_experimental_option('prefs', {
"download.default_directory": "C:/Users", #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(executable_path=DRIVER_PATH,options = chrome_options)
driver.get(url) //url of pdf
time.sleep(3)
pyautogui.press('enter')

推荐阅读