scrapy框架利用start_requests方法改写post请求

scrapy默认发起的是get请求,如果你想发起post请求该怎么办呢?
解决办法就是利用start_request方法,对该方法进行改写,进行post请求。
我们以post请求http://httpbin.org为例子讲解。
我们可能本能的以为改掉start_urls就可以了
例如:

class HttpbinSpider(scrapy.Spider):
    name = 'httpbin'
    allowed_domains = ['httpbin.org']
    start_urls = ['http://httpbin.org/post']

但是结果状态吗是405

2018-08-03 14:39:31 [scrapy.core.engine] DEBUG: Crawled (405) .org/post> (referer: None)
2018-08-03 14:39:32 [scrapy.spidermiddlewares.httperror] INFO: Ignoring response <405 http://httpbin.org/pos
t>: HTTP status code is not handled or not allowed

所以我们必须重写start_request方法。改变里面的url为http://httpbin.org,
method改变为POST,callback为self.parse_post
构建parse_post方法。

  def start_requests(self):
        yield scrapy.Request(url='http://httpbin.org/post',method='POST',callback=self.parse_post)
    def parse(self, response):
        pass

    def parse_post(self,response):
        print("hello",response.text)


输出结果为;

2018-08-03 14:48:06 [scrapy.core.engine] DEBUG: Crawled (200)

你可能感兴趣的:(python,python爬虫程序笔记)