【问题标题】:python webcrawler downloading filespython webcrawler 下载文件
【发布时间】:2012-08-19 10:03:03
【问题描述】:

我有一个网络爬虫,可以搜索某些文件并下载它们,但是当“另存为或打开”对话框提示时,我该如何下载 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()

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    您将需要修改 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')
    

    【讨论】:

    • 我可以自定义保存它的目录吗?
    • @user1582983 是的,所以用 'application/pdf' 切换出该元组中的值(我想 - 我会更新一些你可以复制/粘贴的东西)。至于目录,看我上次的更新。希望有帮助!
    • 由于某种原因它没有下载到目录,当我检查从 firefox 下载时,它也没有在其中列出。
    • @user1582983 是否下载?指定路径的方式可能存在问题。很高兴解决问题。
    • 我的路径目前是C:\Documents and Settings\User\Desktop\web-get project\downloads
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2021-10-10
    • 2021-10-24
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多