我有一个网络爬虫可以搜索某些文件并下载它们,但是当出现“另存为或打开”对话框时,我该如何下载 pdf 文件。我目前正在使用 python selenium 进行爬网。这是我的代码。
from selenium import webdriver
import time
browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://www.tda-sgft.com/TdaWeb/jsp/fondos/Fondos.tda") # Load page
link = browser.find_element_by_link_text("Mortgage Loan")
link.click()
link2 = browser.find_element_by_link_text("ABS")
link2.click()
link3 = browser.find_element_by_link_text("TDA 13 Mixto")
link3.click()
download = browser.find_element_by_link_text("General Fund Information")
download.click()
time.sleep(0.2) # Let the page load, will be added to the API
browser.close()
请您参考如下方法:
您将需要修改您的 Firefox 配置文件的首选项。为了让它停止显示该对话框,您需要设置正在使用的配置文件的 browser.helperApps.neverAsk.saveToDisk 属性。为此,您可以这样做(请注意,这是针对 CSV/Excel 文件的 - 我相信您的类型是“应用程序/pdf”):
profile = webdriver.firefox.firefox_profile.FirefoxProfile()
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', ('text/csv,'
'application/csv,'
'application/msexcel'))
对于你的情况(我还没有用 PDF 测试过这个,所以请对它持保留态度 :)),你可以试试这个:
profile = webdriver.firefox.firefox_profile.FirefoxProfile()
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', ('application/pdf'))
第二个参数是一个元组,其中包含永远不会触发 Save As 提示的文件类型。然后将此配置文件传递到您的浏览器:
browser = webdriver.Firefox(firefox_profile=profile)
现在,当您下载该元组中某种类型的文件时,它应该绕过提示并将其放入您的默认目录中。如果要更改文件下载到的目录,可以使用相同的过程,只需更改几处(在将 profile 附加到浏览器之前执行此操作):
profile.set_preference('browser.download.folderList': 2)
profile.set_preference('browser.download.dir': '/path/to/your/dir')




