簡體   English   中英

提交表單后,抓取下載MIME類型文件

[英]Scrapy download MIME type file after form submission

http://comunicacion.movi​​starplus.es/guiaProgramacion/exportarProgramacion頁中,用戶必須鍵入一些字段以下載最重要的西班牙廣播公司的頻道時間表。 用戶填寫表單並單擊Exportar按鈕后,瀏覽器將自動開始下載擴展名為formato下拉列表的文件。

現在,從我的Chrome瀏覽器中很容易獲取文件。 但是,我想使用一個Scrapy腳本來自動化它,在下面您可以找到我到目前為止所做的:

from scrapy.item import Item, Field
from scrapy.http import FormRequest
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.http import Request

class ProgramacionSpider(Spider):
    name = "Programacion"
    allowed_domains = ["comunicacion.movistarplus.es"]
    start_urls = ["http://comunicacion.movistarplus.es/guiaProgramacion/exportarProgramacion"]

    def parse(self, response):
        yield FormRequest.from_response(response, formname='formExportar', formdata={"fechaInicio": "2017-01-05", "fechaFin": "2017-01-19", "genero" : "0", "selPredefinicion": "0", "formato": "csv", "cadena[]": "{INTECO, ETB}"}, callback=self.parse1)

    def parse1(self, response):
        print response

現在,在使用需要與表單一起發送的POST參數執行FormRequest.from_response之后, Scrapy將使用以下文本進行響應:

2017-01-05 13:19:11 [scrapy] INFO: Scrapy 1.1.2 started (bot: Programacion)
2017-01-05 13:19:11 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'Programacion.spiders', 'FEED_URI': 'sss.csv', 'DUPEFILTER_CLASS': 'scrapy_splash.SplashAwareDupeFilter', 'SPIDER_MODULES': ['Programacion.spiders'], 'BOT_NAME': 'Programacion', 'FEED_FORMAT': 'csv', 'HTTPCACHE_STORAGE': 'scrapy_splash.SplashAwareFSCacheStorage'}
2017-01-05 13:19:11 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.feedexport.FeedExporter',
 'scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2017-01-05 13:19:12 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy_splash.SplashCookiesMiddleware',
 'scrapy_splash.SplashMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-01-05 13:19:12 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy_splash.SplashDeduplicateArgsMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-01-05 13:19:12 [scrapy] INFO: Enabled item pipelines:
[]
2017-01-05 13:19:12 [scrapy] INFO: Spider opened
2017-01-05 13:19:12 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-01-05 13:19:12 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-01-05 13:19:12 [scrapy] DEBUG: Crawled (200) <GET http://comunicacion.movistarplus.es/guiaProgramacion/exportarProgramacion> (referer: None)
2017-01-05 13:19:12 [scrapy] DEBUG: Crawled (200) <POST http://comunicacion.movistarplus.es/guiaProgramacion/exportar> (referer: http://comunicacion.movistarplus.es/guiaProgramacion/exportarProgramacion)
<200 http://comunicacion.movistarplus.es/guiaProgramacion/exportar>
2017-01-05 13:19:12 [scrapy] INFO: Closing spider (finished)
2017-01-05 13:19:12 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 822,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 1,
 'downloader/request_method_count/POST': 1,
 'downloader/response_bytes': 6603,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 1, 5, 12, 19, 12, 783383),
 'log_count/DEBUG': 3,
 'log_count/INFO': 7,
 'request_depth_max': 1,
 'response_received_count': 2,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'start_time': datetime.datetime(2017, 1, 5, 12, 19, 12, 204111)}
2017-01-05 13:19:12 [scrapy] INFO: Spider closed (finished)

顯然,搜尋器似乎可以正常工作,因為它沒有響應500錯誤(即,它接受來自表單的POST變量)。

問題

我想知道如何使用Scrapy直接下載文件,而對如何做到這一點沒有一個想法。 謝謝。

您正在談論的文件在您收到的響應中,更確切地說,它是在response.body屬性中。

您可以簡單地打開一個文件,並將response.body的內容寫入其中。 像這樣:

def parse(self, response):
    # check if response is valid
    if response.status != 200:
        print("failed to get schedule")
        return
    # save to file valid response
    with open('results.csv', 'w') as f:
        f.write(response.body)    

編輯:我發現您的formdata有問題,這是返回空文件的原因:

def parse(self, response):
    formdata={"fechaInicio": "2017-01-05", 
              "fechaFin": "2017-01-19", 
              "genero": "0",
              "selPredefinicion": "0", 
              "formato": "csv",
              # "cadena[]": "{INTECO, ETB}",  # incorrect
              "cadena[]": ["INTECO", "ETB"]}  # <---- this is correct
    yield FormRequest.from_response(response, formname='formExportar', 
                                    formdata=formdata,
                                    callback=self.parse1)

您在此處提供的字符串(而不是列表)不正確,上面的示例是正確的,並且正確地返回/保存了結果。

暫無
暫無

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

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