簡體   English   中英

python webcrawler 下載文件

[英]python webcrawler downloading files

我有一個網絡爬蟲,可以搜索某些文件並下載它們,但是當“另存為或打開”對話框提示時,我如何下載 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

browser = webdriver.Firefox(firefox_profile=profile)

現在,當您下載該元組中某個類型的文件時,它應該繞過提示並將其放在您的默認目錄中。 如果要更改文件下載到的目錄,可以使用相同的過程,只需更改一些內容(在將profile附加到瀏覽器之前執行此操作):

profile.set_preference('browser.download.folderList': 2)
profile.set_preference('browser.download.dir': '/path/to/your/dir')

暫無
暫無

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

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