1.scrapy 爬网站 显示 Filtered offsite request to 错误.
爬取京东商品时出现:DEBUG: Filtered offsite request to 'item.jd.com': <GET https://item.jd.com/39652897238.html>
官方对这个的解释,是你要request的地址和allow_domain里面的冲突,从而被过滤掉。所以有两种方法解决:
1)将allow_domain中域名设置更宽泛,如
allowed_domains = ['search.jd.com'] 设置为 allowed_domains = ['jd.com']
2)在yield中使用不过滤请求字段 dont_filter=True,如:yield Request(url, callback=self.parse_item, dont_filter=True)
2.出现: HTTP status code is not handled or not allowed
settings中 Ignoring response <301 https://item.jd.com/44133061670.html>: HTTP status code is not handled or not allowed
这是因为我在settings中设置了禁止重定向,遇到30x响应码时就会出现这种情况,解决办法:
在settings中添加
HTTPERROR_ALLOWED_CODES = [301]#上面报的是301,就把301加入。程序就继续执行啦。
在scrapy中,当爬取的网站需要登录才能获取数据时,要讲cookie单独拿出来,不能放在headers中,同时需要将COOKIES_ENABLE设置为Ture,设置cookie的方式有两种:
2.DownloadMiddleware
settings中给downloadmiddleware解注释
去中间件文件中找downloadmiddleware这个类,修改process_request,添加request.cookies={}即可。
3.爬虫主文件中重写start_request
def start_requests(self):
yield scrapy.Request(url,dont_filter=True,cookies={自己的cookie})