前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >分布式爬虫搭建系列 之三---scrapy框架初用

分布式爬虫搭建系列 之三---scrapy框架初用

作者头像
wfaceboss
发布2019-04-08 10:48:49
5480
发布2019-04-08 10:48:49
举报
文章被收录于专栏:wfacebosswfaceboss

第一,scrapy框架的安装

通过命令提示符进行安装(如果没有安装的话)

代码语言:javascript
复制
pip install Scrapy

如果需要卸载的话使用命令为:

代码语言:javascript
复制
pip uninstall Scrapy

第二,scrapy框架的使用

先通过命令提示符创建项目,运行命令:

代码语言:javascript
复制
scrapy startproject crawlquote#crawlquote这是我起的项目名

其次,通过我们的神器PyCharm打开我们的项目--crawlquote(也可以将PyCharm打开我们使用虚拟环境创建的项目)

然后,打开PyCharm的Terminal,如图

然后在命令框中输入

代码语言:javascript
复制
scrapy genspider quotes quotes.toscrape.com

此时的代码目录为:

 文件说明:

  • scrapy.cfg  项目的配置信息,主要为Scrapy命令行工具提供一个基础的配置信息。(真正爬虫相关的配置信息在settings.py文件中)
  • items.py    设置数据存储模板,用于结构化数据,如:Django的Model
  • pipelines    数据处理行为,如:一般结构化的数据持久化
  • settings.py 配置文件,如:递归的层数、并发数,延迟下载等
  • spiders      爬虫目录,如:创建文件,编写爬虫规则

            quotes.py使我们书写的爬虫---里面是发起请求-->拿到数据---->临时存储到item.py中

 运行爬虫命令为:

代码语言:javascript
复制
scrapy crawl quotes

 第三,使用scrapy的基本流程

(1)明确需要爬取的数据有哪些

(2)分析页面结构知道需要爬取的内容在页面中的存在形式

(3)在item.py中定义需要爬取的数据的存储字段

(4)书写爬虫  -spider中定义(spiders中的quotes.py) --数据重新格式化化后在item.py中存储

(5)管道中--pipeline.py ----对item里面的内容在加工 , 以及定义链接数据库的管道

(6)配置文件中----settings.py中开启管道作用:ITEM_PIPELINES ,定义数据库的名称,以及链接地址   

(7)中间件中----middlewares.py  

根据上述的一个简单的代码演示:

1)item.py中

代码语言:javascript
复制
import scrapy


class CrawlquoteItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    text = scrapy.Field()
    author = scrapy.Field()
    tags = scrapy.Field()

2)spiders--quotes(爬虫)

代码语言:javascript
复制
# -*- coding: utf-8 -*-
import scrapy
from  crawlquote.items import CrawlquoteItem


class QuotesSpider(scrapy.Spider):
    name = 'quotes'
    allowed_domains = ['quotes.toscrape.com']
    start_urls = ['http://quotes.toscrape.com/']

    def parse(self, response):
        quotes = response.css('.quote')
        for quote in quotes:
            item = CrawlquoteItem()
            text = quote.css('.text::text').extract_first()  # 获取一个
            author = quote.css('.author::text').extract_first()
            tags = quote.css('.tags .tag::text').extract()
            item['text'] = text
            item['author'] = author
            item['tags'] = tags
            yield item  # 将网页中的内容重新生成一个item以便于后面的认识

        next = response.css('.pager .next a::attr(href)').extract_first()
        url = response.urljoin(next)  # urljoin翻页
        yield scrapy.Request(url=url, callback=self.parse)  # 递归调用

3)pipeline.py中

代码语言:javascript
复制
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
from scrapy.exceptions import DropItem


class TextPipeline(object):
    def __init__(self):
        self.limit = 50

    def process_item(self, item, spider):  # 对重新生成的item进行再制作
        if item['text']:
            if len(item['text']) > self.limit:
                item['text'] = item['text'][0:self.limit].rstrip() + '...'
            return item
        else:
            return DropItem('Missing Text')


class MongoPipeline(object):  # 与数据库有关的操作
    def __init__(self, mongo_uri, mongo_db):  # (2) MongoPipeline构造函数
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):  # (1)读取settings里面的值,类方法
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DB')
        )

    def open_spider(self, spider):  # (3)爬虫启动时需要的操作
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def process_item(self, item, spider):  # 保存到mongodb数据库
        name = item.__class__.__name__
        self.db[name].insert(dict(item))
        return item

    def close_spider(self, spider):  # 关闭mongodb
        self.client.close()

4)settings.py中

代码语言:javascript
复制
BOT_NAME = 'crawlquote'

SPIDER_MODULES = ['crawlquote.spiders']
NEWSPIDER_MODULE = 'crawlquote.spiders'

#数据库链接
MONGO_URI = 'localhost'
MONGO_DB = 'crawlquote'

#项目管道开启
ITEM_PIPELINES = {
    'crawlquote.pipelines.TextPipeline': 300,
    'crawlquote.pipelines.MongoPipeline': 400,
}

5)此处还没有用的middelwares.py

总结一下:

针对某部分数据的爬取,先要在item中定义字段,然后在爬虫程序中通过选择器拿到数据并存储到item中,再然后通过pipeline的在加工+setting文件修改--存储到数据库中。此时简单爬取就实现了。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-12-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
消息队列 TDMQ
消息队列 TDMQ (Tencent Distributed Message Queue)是腾讯基于 Apache Pulsar 自研的一个云原生消息中间件系列,其中包含兼容Pulsar、RabbitMQ、RocketMQ 等协议的消息队列子产品,得益于其底层计算与存储分离的架构,TDMQ 具备良好的弹性伸缩以及故障恢复能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档