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

一直用的是通用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
posted @   seozed  阅读(1193)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示