Scrapy - Crawlspider 内置爬虫

Scrapy之CrawlSpider爬虫开发

接着前一篇通过基础爬虫对问答频道文章的采集,下面我们试用一下Scrapy工具箱中几个不错的功能。

由于大部分数据爬取工作具有相似性、一致性,所以Scrapy特别提供了若干个 更高程度封装的通用爬虫类 来协助我们更快速、高效的完成爬虫开发工作

#查看scrapy提供的通用爬虫(Generic Spiders)
scrapy genspider -l
CrawlSpider

CrawlSpider 是通用爬虫里最常用的一个
通过一套规则引擎,它自动实现了页面链接的搜索跟进,解决了包含但不限于自动采集详情页、跟进分类/分页地址等问题 最后,我们仅仅需要开发实现 ’详情页解析器‘ 逻辑便能完成爬虫开发工作

这里我们以爬取马蜂窝北京行程资源( http://www.mafengwo.cn/xc/10065/ )为例:

#基于通用爬虫模板创建爬虫
scrapy genspider --template crawl xinchen www.mafengwo.cn/xc/10065

然后我们设计以下的具体爬虫逻辑,编辑文件 mafengwo/mafengwo/spiders/xinchen.py
为了方便演示,本例中我们把相关的爬虫主逻辑、持久化逻辑,数据建模逻辑等等都封装在该爬虫文件中

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
import pymongo


class XinchenSpider(CrawlSpider):
    name = 'xinchen'
    allowed_domains = ['www.mafengwo.cn']
    start_urls = ['http://www.mafengwo.cn/xc/10065/']

    rules = (
        # 提取下一页链接并跟进
        Rule(
            LinkExtractor(allow=r'/xc/10065/(\d+).html', restrict_xpaths='//div[@class="page-hotel"]/a[@class="ti next"]'),
            callback=None, follow=True
        ),

        # 提取详情页链接,并使用parse_item解析器抓取数据
        Rule(
            LinkExtractor(allow=r'/schedule/(\d+).html', restrict_xpaths='//div[@class="post-list"]/ul/li/dl/dt/a'),
            callback='parse_item', follow=False
        ),
    )

    def __init__(self, *args, **kwargs):
        super(XinchenSpider, self).__init__(*args, **kwargs) #调用父类方法
        #mongo配置
        self.client = pymongo.MongoClient('localhost')
        self.collection = self.client['mafengwo']['xinchen_pages']

    def closed(spider, reason):
        self.client.close()

    def parse_item(self, response):
        item = {}
        item['url'] = response.url
        item['author'] = response.xpath('//dl[@class="flt1 show_from clearfix"]/dd/p/a[@class="name"]').extract_first()
        item['title'] = response.xpath('//p[@class="dd_top"]/a/text()').extract_first()
        item['content'] = response.xpath('//div[@class="guide"]').extract_first()
        self.collection.update({'url': item['url']}, item, upsert=True) #排重式的往mongo中插入数据
        yield item

运行爬虫

scrapy crawl --nolog xinchen

转载于:https://my.oschina.net/u/2400083/blog/735888

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值