我将settings.py
中的默认请求头更改如下:
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
已启用,但连接已完全关闭,就像未设置头一样
这是温泉浴池:
# -*- 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
来设置头,那么一切都会正常工作
# -*- 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中解决
我看到,在使用默认标头中间件时,用户代理标头确实没有正确设置,并且这个特定的站点拒绝没有预期的用户代理标头的连接
为爬虫程序设置用户代理的推荐方法是使用用户代理设置密钥:
例如
在使用默认标题时不设置用户代理可能是Scrapy中的一些错误,或者这可能是预期的,并在某处记录。您需要对此做更多的研究,如果它确实是一个bug,那么值得在Scrapy github repo中发布bug报告
相关问题 更多 >
编程相关推荐