实现爬虫的增量式爬取有两种方法,一是在获得页面解析的内容后判断该内容是否已经被爬取过,二是在发送请求之前判断要被请求的url是否已经被爬取过,前一种方法可以感知每个页面的内容是否发生变化,能获取页面新增或者变化的内容,但是由于要对每个url发送请求,所以速度比较慢,而对网站服务器的压力也比较大,后一种无法获得页面变化的内容,但是因为不用对已经爬取过的url发送请求,所以对服务器压力比较小,速度比较快,适用于爬取新增网页,下面用一个小说网站爬虫的例子来介绍在scrapy中这两种方式的实现
1.要爬取的信息
在scrapy中,信息通过item来封装,这里我定义两个item,一个用于封装每本小说的信息,一个用于封装每个章节的信息
1.BookItem
class BookItem(scrapy.Item):
_id = scrapy.Field() #小说id,用于定位章节信息,章节唯一
novel_Name = scrapy.Field() #小说名称
novel_Writer = scrapy.Field()#小说作者
novel_Type = scrapy.Field()#小说类型
novel_Status = scrapy.Field()#小说状态,连载或者完结
novel_UpdateTime = scrapy.Field()#最后更新时间
novel_Words = scrapy.Field() #总字数
novel_ImageUrl = scrapy.Field()#封面图片
novel_AllClick = scrapy.Field()#总点击
novel_MonthClick = scrapy.Field()#月点击
novel_WeekClick = scrapy.Field()#周点击
novel_AllComm = scrapy.Field()#总推荐
novel_MonthComm = scrapy.Field()#月推荐
novel_WeekComm = scrapy.Field()#周推荐
novel_Url = scrapy.Field()#小说url
novel_Introduction = scrapy.Field()#小说简介
2.ChapterItem
class ChapterItem(scrapy.Item):
chapter_Url = scrapy.Field()#章节url
_id = scrapy.Field()#章节id
novel_Name = scrapy.Field()#小说名称
chapter_Name = scrapy.Field()#章节名称
chapter_Content = scrapy.Field()#内容
novel_ID = scrapy.Field()#小说id
is_Error = scrapy.Field()#是否异常
2.解析信息
这里我是用的是scrapy自带的通用爬虫模块,只需要指定信息解析方式,需要跟进的url就够了
1.指定需要跟进的url和回调函数
allowed_domains = [“23us.so”] #允许爬取的域名
start_urls = [“http://www.23us.so/xiaoshuo/414.html”]#种子url
#跟进的url
rules=(
Rule(LinkExtractor(allow=(“xiaoshuo/\d*.html”)),callback=“parse_book_message”,follow=True),
Rule(LinkExtractor(allow=(“files/article/html/\d*?/\d*?.index.html”)),callback=“parse_book_chapter”,follow=True),
Rule(LinkExtractor(allow=(“files/article/html/\d*?/\d*?/\d*?.html”)),callback=“parse_chapter_content”,follow