scrapy 域名过滤。DEBUG: Filtered offsite request to 解决方案

在做爬虫项目时,出现了一个问题,解析一个网站二次爬取时没有获取到数据,就写了一个测试程序试了下,测试程序如下

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class ZhenaiSpider(CrawlSpider):
    name = ‘zhenai’
    allowed_domains = [‘www.zhenai.com’]
    start_urls = [‘http://www.zhenai.com/zhenghun/beijing/1’]

    rules = (
        Rule(LinkExtractor(allow=r’http://www.zhenai.com/zhenghun/beijing/\d+’), callback=’parse_item’, follow=False),
    )

    def parse_item(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’: ,原来是二次解析的域名被过滤掉了,解决办法

解决办法一: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’] 即更换为对应的一级域名

发表评论

邮箱地址不会被公开。 必填项已用*标注