一直用的是通用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
這個名字。
參考資料: