鍍金池/ 問答/人工智能  數(shù)據(jù)分析&挖掘  Python/ Python scrapy.Request 無法下載網(wǎng)頁

Python scrapy.Request 無法下載網(wǎng)頁

使用 scrapy.Request 方法來采集頁面,但是卻沒有任何執(zhí)行。

import scrapy
def ret(response):
    print('start print')
    print(response.body)


url = 'https://doc.scrapy.org/en/latest/intro/tutorial.html'
v = scrapy.http.Request(url=url, callback=ret)
print(url, v)

輸出內(nèi)容:

https://doc.scrapy.org/en/latest/intro/tutorial.html
<GET https://doc.scrapy.org/en/latest/intro/tutorial.html>

方法ret完全就沒有執(zhí)行,無法打印出對(duì)應(yīng)的內(nèi)容

回答
編輯回答
命多硬

你只是定義了一個(gè)Request, 定義好的Request自己并不去去建立網(wǎng)絡(luò)聯(lián)接并下載, 而是能過scrapy的Downloader和Spider來完成.
參考官方文檔:

一般來說,Request 對(duì)象在spiders中被生成并且最終傳遞到 下載器(Downloader),下載器對(duì)其進(jìn)行處理并返回一個(gè) Response 對(duì)象, Response 對(duì)象還會(huì)返回到生成request的spider中。

如果想讓他運(yùn)行, 可以定義如下的spider

import scrapy
from scrapy.spiders import CrawlSpider, Rule

url = 'https://doc.scrapy.org/en/latest/intro/tutorial.html'


def ret(response):
    print('start print\n')
    print(response.body)

def errorcb(err):
    print(err+"\n")
    pass



class MySpider(CrawlSpider):
    name="test"
    def start_requests(self):
        return [scrapy.http.Request(url=url, callback=ret, errback=errorcb)]

保存成文件scrapy_cb.py, 然后通過

scrapy runspider scrapy_cb.py 

來運(yùn)行

2018年7月4日 15:07