问题来自于在运行spider过程中,pipeline当中写入的数据库存储过程始终得不到item传递的数据,经调试,发现了pipeline被调用的机制。
写一段代码来测试:
spider.py:
import scrapy
from items import Work1Item #自定义的item,用于结构化数据
class Work1Spider(scrapy.Spider):
name = 'work1'
start_urls = [
'http://quotes.toscrape.com/',
]
def parse(self, response):
for quote in response.xpath('//div[@class="quote"]'):
item = Work1Item()
item['author'] = quote.xpath('.//small[@class="author"]/text()').extract_first()
item['tags'] = quote.xpath('.//div[@class="tags"]/a[@class="tag"]/text()').extract()
item['quote'] = quote.xpath('./span[@class="text"]/text()').extract_first()
next_page_url = response.xpath('//li[@class="next"]/a/@href').extract_first()
if next_page_url is not None:
yield scrapy.Request(response.urljoin(next_page_url))
pipeline.py:
class Work1Pipeline(object):
def process_item(self, item, spider):
print item
return item
settings.py当中开启pipeline:ITEM_PIPELINES = {
'work1.pipelines.Work1Pipeline': 300,
}
运行结果发现item并没有被print。
也就是说在某片代码中缺少了成分,使得pipeline并没有获取到item。
经过调试发现在spider.py中的parse()内部,在我们得到next_page_url之前,加上“yield item”,一切就搞定了。
所以,pipeline是在爬取过程中返回item时调用的,pipeline对item处理后返回item,以便对下一个item进行处理。