首页 > 其他 > 详细

scrapy 使用crawlspider rule不起作用的解决方案

时间:2019-06-05 00:37:00      阅读:260      评论:0      收藏:0      [点我收藏+]

一直用的是通用spider,今天刚好想用下CrawlSpider来抓下数据。结果Debug了半天,一直没法进入详情页的解析逻辑。。

爬虫代码是这样的

# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor


class BeihaireSpider(CrawlSpider):
    name = 'example'
    allowed_domains = ['example.gov.cn']
    start_urls = [
        'http://www.example.gov.cn/2j.asp?numberbj=13&id=106',
    ]
    rules = (
        Rule(LinkExtractor(allow=('unid',)), callback='parse'),
    )

    def parse(self, response):
        print(response.url)

Google、Baidu了好久,没找到原因,不知道是关键字搜索不够精准还是咋的。

然后就去翻Scrapy的文档,结果发现是parse函数的问题。

官方文档中关于crawlspider的一句话:

When writing crawl spider rules, avoid using parse as callback, since the CrawlSpider uses the parse method itself to implement its logic. So if you override the parse method, the crawl spider will no longer work.

终于找到原因了,原来crawlspider的实现用了parse函数来解析页面。而我,把它给覆盖了,所以一进到parse函数,爬虫就抓取结束了。。啥也没干

解决方案

解析Response函数不要使用parse这个名字。

参考资料:

  1. <https://docs.scrapy.org/en/latest/topics/spiders.html?highlight=crawlspider#crawling-rules

scrapy 使用crawlspider rule不起作用的解决方案

原文:https://www.cnblogs.com/seozed/p/10977051.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!