3

我正在尝试使用scrapy和scrapy-splash获取请求状态代码,下面是蜘蛛代码。

class Exp10itSpider(scrapy.Spider):
    name = "exp10it"

    def start_requests(self):
        urls = [
                'http://192.168.8.240:8000/xxxx' 
        ]
        for url in urls:
            #yield SplashRequest(url, self.parse, args={'wait': 0.5, 'dont_redirect': True},meta={'handle_httpstatus_all': True})
            #yield scrapy.Request(url, self.parse, meta={'handle_httpstatus_all': True})
            yield scrapy.Request(url, self.parse, meta={'handle_httpstatus_all': True,'splash': {
                'args': {
                    'html': 1,
                    'png': 1,
                    }
            }
            }
            )


    def parse(self, response):
        input("start .........")
        print("status code is:\n")
        input(response.status)

我的起始 urlhttp://192.168.8.240:8000/xxxx是一个 404 状态码 url,有三种请求方式:

第一个是:

yield SplashRequest(url, self.parse, args={'wait': 0.5, 'dont_redirect': True},meta={'handle_httpstatus_all': True})

第二个是:

yield scrapy.Request(url, self.parse, meta={'handle_httpstatus_all': True})

第三个是:

yield scrapy.Request(url, self.parse, meta={'handle_httpstatus_all': True,'splash': {
            'args': {
                'html': 1,
                'png': 1,
                }
        }
        }
        )

只有第二种请求方式yield scrapy.Request(url, self.parse, meta={'handle_httpstatus_all': True})可以获得正确的状态码404,第一种和第三种都可以获得状态码200,也就是说,我尝试使用scrapy-splash后,我无法获得正确的状态码404,你能帮帮我吗?

4

1 回答 1

3

正如文档scrapy-splash建议的那样,您必须通过magic_response=TrueSplashRequest实现这一点:

meta['splash']['http_status_from_error_code']-失败时设置response.status为 HTTP 错误代码;assert(splash:go(..))它需要meta['splash']['magic_response']=True. http_status_from_error_code如果您使用原始元 API,则选项False默认为;SplashRequest默认情况下将其设置为True

编辑: 不过,我只能让它与execute端点一起工作。这是使用httpbin.org测试 HTTP 状态代码的示例蜘蛛:

# -*- coding: utf-8 -*-
import scrapy
import scrapy_splash

class HttpStatusSpider(scrapy.Spider):
    name = 'httpstatus'

    lua_script = """
    function main(splash, args)
      assert(splash:go(args.url))
      assert(splash:wait(0.5))
      return {
        html = splash:html(),
        png = splash:png(),
      }
    end
    """

    def start_requests(self):
        yield scrapy_splash.SplashRequest(
            'https://httpbin.org/status/402', self.parse,
            endpoint='execute',
            magic_response=True,
            meta={'handle_httpstatus_all': True},
            args={'lua_source': self.lua_script})

    def parse(self, response):
        pass

它将 HTTP 402 状态代码传递给 Scrapy,从输出中可以看出:

...
2017-10-23 08:41:31 [scrapy.core.engine] DEBUG: Crawled (402) <GET https://httpbin.org/status/402 via http://localhost:8050/execute> (referer: None)
...

您也可以尝试其他 HTTP 状态代码。

于 2017-10-20T06:25:51.733 回答