Scrapy 错误:用户超时导致连接失败

Rav*_*ven 4 python twisted scrapy

我正在使用 scrapy 来抓取阿迪达斯网站:http://www.adidas.com/us/men-shoes。但它总是显示错误:

用户超时导致连接失败:获取http://www.adidas.com/us/men-shoes花费的时间超过 180.0 秒..

它重试了 5 次,然后完全失败。

我可以访问 chrome 上的 url,但它在scrapy 上不起作用。
我试过使用自定义用户代理并模拟标头请求,但它仍然不起作用。

下面是我的代码:

import scrapy


class AdidasSpider(scrapy.Spider):
    name = "adidas"

    def start_requests(self):

        urls = ['http://www.adidas.com/us/men-shoes']

        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "en-US,en;q=0.9",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            "Host": "www.adidas.com",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
        }

        for url in urls:
            yield scrapy.Request(url, self.parse, headers=headers)

    def parse(self, response):
        yield(response.body)
Run Code Online (Sandbox Code Playgroud)

爬虫日志:

{'downloader/exception_count': 1,
 'downloader/exception_type_count/twisted.web._newclient.ResponseNeverReceived': 1,
 'downloader/request_bytes': 224,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'finish_reason': 'shutdown',
 'finish_time': datetime.datetime(2018, 1, 25, 10, 59, 35, 57000),
 'log_count/DEBUG': 2,
 'log_count/INFO': 9,
 'retry/count': 1,
 'retry/reason_count/twisted.web._newclient.ResponseNeverReceived': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'start_time': datetime.datetime(2018, 1, 25, 10, 58, 39, 550000)}
Run Code Online (Sandbox Code Playgroud)

更新

在使用 fiddler 查看请求标头并进行一些测试后,我发现了导致问题的原因。ScrapyConnection: close默认发送一个标头,因此我没有从阿迪达斯网站得到任何响应。

在此处输入图片说明

通过发出相同的请求但没有Connection: close标头对提琴手进行测试后,我得到了正确的响应。现在的问题是如何删除Connection: close标题?

在此处输入图片说明

Rav*_*ven 5

由于scrapy 不允许您编辑Connection: close标题。我改用scrapy-splash 来使用splash 发出请求。

现在Connection: close标题可以被覆盖并且现在一切正常。缺点是现在网页必须在我从飞溅中获得响应之前加载所有资产,速度较慢但有效。

Scrapy 应该添加选项来编辑它们的默认Connection: close标题。它在库中被硬编码,不能轻易覆盖。

下面是我的工作代码:

headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.9",
        "Host": "www.adidas.com",
        "Connection": "keep-alive",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
    }

    def start_requests(self):
        url = "http://www.adidas.com/us/men-shoes?sz=120&start=0"
        yield SplashRequest(url, self.parse, headers=self.headers)
Run Code Online (Sandbox Code Playgroud)