Scrapy抓取到网页数据,保存到数据库,是通过pipelines来处理的。看一下官方文档的说明。
当Item在Spider中被收集之后,它将会被传递到Item Pipeline,一些组件会按照一定的顺序执行对Item的处理。
以下是item pipeline的一些典型应用:
清理HTML数据
验证爬取的数据(检查item包含某些字段)
查重(并丢弃)
将爬取结果保存到数据库中
一、解析页面数据 Spider类
本文以简书《读书》专题为例,抓取专题收录的所有文章数据,http://www.jianshu.com/collection/yD9GAd
把需要爬取的页面数据解析出来,封装成对象Item,提交(yield)。
item = JsArticleItem()
author = info.xpath('p/a/text()').extract()
pubday = info.xpath('p/span/@data-shared-at').extract()
author_url = info.xpath('p/a/@href').extract()
title = info.xpath('h4/a/text()').extract()
url = info.xpath('h4/a/@href').extract()
reads = info.xpath('div/a[1]/text()').extract()
reads = filter(str.isdigit, str(reads[0])