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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM