CrawlSpider一直無法進入回撥函式
阿新 • • 發佈:2020-07-26
CrawlSpider一直無法進入回撥函式的
碰到的兩個坑:
1、正則表示式寫的不對
start_urls = ['http://wz.sun0769.com/political/index/politicsNewest?id=1&page=1'] link = LinkExtractor(allow=r'id=1&page=\d+')
2、回撥函式中的xpath路徑寫的不對
附本次程式碼:
import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from sunCrawlSpider.items import SuncrawlspiderItem from sunCrawlSpider.items import Detail_item class SunSpider(CrawlSpider): name = 'sun' # allowed_domains = ['www.xxx.com'] start_urls = ['http://wz.sun0769.com/political/index/politicsNewest?id=1&page=1'] link = LinkExtractor(allow=r'id=1&page=\d+') link_detail = LinkExtractor(allow=r'political/politics/index\?id=\d+') rules = ( Rule(link, callback='parse_item', follow=False), Rule(link_detail, callback='parse_detail', follow=False), ) def parse_item(self, response): li_list = response.xpath('/html/body/div[2]/div[3]/ul[2]/li') for li in li_list: num = li.xpath('./span[1]/text()').extract_first() title = li.xpath('./span[3]/a/text()').extract_first() # url = 'http://wz.sun0769.com/' + li.xpath('./span[3]/a/@href').extract_first() item = SuncrawlspiderItem() item['title'] = title item['num'] = num yield item def parse_detail(self, response): content = response.xpath('/html/body/div[3]/div[2]/div[2]/div[2]/pre/text()').extract_first() num = response.xpath('/html/body/div[3]/div[2]/div[2]/div[1]/span[4]/text()').extract_first() num = num.split(':')[-1] item = Detail_item() item['num'] = num item['content'] = content yield item