python - Scrapy DEFAULT_REQUEST_HEADERS 不起作用

标签 python scrapy

我在 settings.py 中更改了默认请求 header ,如下所示:

DEFAULT_REQUEST_HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
}

但是,它在我的 HotSpider 中不起作用。我可以看到 scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware 已启用,但连接已完全关闭,就好像未设置 header 一样。

这是 HotSpider:

    # -*- coding: utf-8 -*-
    import scrapy
    
    class HotSpider(scrapy.Spider):
        name = "hot"
        allowed_domains = ["qiushibaike.com"]
        start_urls = (
            'http://www.qiushibaike.com/hot',
        )
        
        def parse(self, response):
            print '\n', response.status, '\n'

如果我更改代码以覆盖 make_requests_from_url 以设置 header ,则一切正常。

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


    class HotSpider(scrapy.Spider):
        name = "hot"
        allowed_domains = ["qiushibaike.com"]
        start_urls = (
            'http://www.qiushibaike.com/hot',
        )
        headers =  {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate, sdch',
            'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
        }
    
        def make_requests_from_url(self, url):
            return scrapy.http.Request(url, headers=self.headers)
    
    
        def parse(self, response):
            print '\n', response.status, '\n'

这个问题会根据prioritize default headers over user agent middlewares #2091在Scrapy 1.2中解决。

最佳答案

我发现在使用默认 header 中间件时,User-Agent header 确实未正确设置,并且此特定站点拒绝没有预期用户代理 header 的连接。

为爬虫设置用户代理的推荐方法是使用 USER_AGENT 设置键:

例如

# settings.py
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"

在使用默认 header 时不设置用户代理可能是 Scrapy 中的一些错误,或者这可能是预期的并在某处记录。你需要对此做更多的研究,如果它确实是错误,那么值得在 Scrapy github repo 中发布错误报告。

关于python - Scrapy DEFAULT_REQUEST_HEADERS 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38186221/

相关文章:

python - 无法使用 scrapy 提取分页链接

python - 在 Celery 任务中运行 Scrapy 蜘蛛

python - “用户”对象没有属性 'is_verified'

python - 为什么当第二个参数为 "open"时,python 函数 "w"会自动创建文件?

从 python 解释器调用时的 Python argparse

python - 存储从Python脚本中执行的curl命令的内容

python - Kivy:如何向文本输入添加填充

python - 在 Scrapy 中获取 http.response 对象的最简单方法

python - 如何将抓取的项目保存到多个 .jl 文件?

python - scrapy - 如果跟随无限网站则终止抓取