在做爬虫项目时,出现了一个问题,解析一个网站二次爬取时没有获取到数据,结果报错DEBUG: Filtered offsite request to...
import scrapy
class ZhenaiSpider(CrawlSpider):
name = 'zhenai'
allowed_domains = ['www.zhenai.com']
start_urls = ['http://www.zhenai.com/zhenghun/beijing/1']
def parse(self, response):
a_list = response.xpath('//div[@class="content"]/table//tr/th/a')
for a in a_list:
item = {}
title = a.xpath('./text()').extract_first()
item['title'] = title
detail_url = a.xpath('./@href').extract_first()
yield scrapy.Request(url=detail_url, meta={'item': item}, callback=self.parse_info)
def parse_info(self, response):
print('ok')
item = response.meta['item']
yield item
结果无法打印ok字符, 也没有错误日志出现
打开调试模式,发现 [scrapy.spidermiddlewares.offsite] DEBUG: Filtered offsite request to 'album.zhenai.com': <GET http://album.zhenai.com/u/109625287>,原来是二次解析的域名被过滤掉了,解决办法
-
解决办法一:
yield scrapy.Request(url=detail_url, meta={'item': item}, callback=self.parse_info, dont_filter=True)
原理:忽略allowed_domains的过滤
-
解决办法二:
将allowed_domains = ['www.zhenai.com']更改为allowed_domains = ['zhenai.com'] 即更换为对应的一级域名