scrapy的建模及管道的使用

一、数据建模

通常在做项目的过程中,在items.py中进行数据建模

  1. 为什么建模

定义item即提前规划好哪些字段需要抓,防止手误,因为定义好之后,在运行过程中,系统会自动检查,配合注释一起可以清晰的知道要抓取哪些字段,没有定义的字段不能抓取,在目标字段少的时候可以使用字典代替。使用scrapy的一些特定组件需要Item做支持,如scrapy的ImagesPipeline管道类,百度搜索了解更多

  1. 如何建模

在items.py文件中定义要提取的字段:

python 复制代码
class MyspiderItem(scrapy.Item): 
    name = scrapy.Field()   # 讲师的名字
    title = scrapy.Field()  # 讲师的职称
    desc = scrapy.Field()   # 讲师的介绍
  1. 如何使用模板类

模板类定义以后需要在爬虫中导入并且实例化,之后的使用方法和使用字典相同

python 复制代码
from myspider.items import MyspiderItem   # 导入Item,注意路径
...
    def parse(self, response)

        item = MyspiderItem() # 实例化后可直接使用

        item['name'] = node.xpath('./h3/text()').extract_first()
        item['title'] = node.xpath('./h4/text()').extract_first()
        item['desc'] = node.xpath('./p/text()').extract_first()
        print(item)
  1. 注意:

from myspider.items import MyspiderItem这一行代码中 注意item的正确导入路径,忽略pycharm标记的错误

python中的导入路径要诀:从哪里开始运行,就从哪里开始导入

二、管道的使用

  1. pipeline中常用的方法:
  • process_item(self,item,spider): 管道类中必须有的函数 实现对item数据的处理 必须return item
  • open_spider(self, spider): 在爬虫开启的时候仅执行一次
  • close_spider(self, spider): 在爬虫关闭的时候仅执行一次
  1. 管道文件的修改

在pipelines.py代码中完善

python 复制代码
import json
from pymongo import MongoClient

class BaiduFilePipeline(object):
    def open_spider(self, spider):  # 在爬虫开启的时候仅执行一次
        if spider.name == 'baidu':
            self.f = open('json.txt', 'a', encoding='utf-8')

    def close_spider(self, spider):  # 在爬虫关闭的时候仅执行一次
        if spider.name == 'baidu':
            self.f.close()

    def process_item(self, item, spider):
        if spider.name == 'baidu':
            self.f.write(json.dumps(dict(item), ensure_ascii=False, indent=2) + ',\n')
        # 不return的情况下,另一个权重较低的pipeline将不会获得item
        return item  

class WangyiMongoPipeline(object):
    def open_spider(self, spider):  # 在爬虫开启的时候仅执行一次
        if spider.name == 'baidu':
        # 也可以使用isinstanc函数来区分爬虫类:
            con = MongoClient(host='127.0.0.1', port=27017) # 实例化mongoclient
            self.collection = con.baidu.teachers # 创建数据库名为baidu,集合名为teachers的集合操作对象

    def process_item(self, item, spider):
        if spider.name == 'baidu':
            self.collection.insert(item) 
            # 此时item对象必须是一个字典,再插入
            # 如果此时item是BaseItem则需要先转换为字典:dict(BaseItem)
        # 不return的情况下,另一个权重较低的pipeline将不会获得item
        return item
  1. 开启管道

在settings.py设置开启pipeline

python 复制代码
ITEM_PIPELINES = {
    'myspider.pipelines.ItcastFilePipeline': 400, # 400表示权重
    'myspider.pipelines.ItcastMongoPipeline': 500, # 权重值越小,越优先执行!
}
  1. 思考:在settings中能够开启多个管道,为什么需要开启多个?

不同的pipeline可以处理不同爬虫的数据,通过spider.name属性来区分,不同的pipeline能够对一个或多个爬虫进行不同的数据处理的操作,比如一个进行数据清洗,一个进行数据的保存同一个管道类也可以处理不同爬虫的数据,通过spider.name属性来区分

  1. pipeline使用注意点
  1. 使用之前需要在settings中开启
  2. ipeline在setting中键表示位置(即pipeline在项目中的位置可以自定义),值表示距离引擎的远近,越近数据会越先经过:权重值小的优先执行
  3. 有多个pipeline的时候,process_item的方法必须return item,否则后一个pipeline取到的数据为None值
  4. pipeline中process_item的方法必须有,否则item没有办法接受和处理
  5. process_item方法接受item和spider,其中spider表示当前传递item过来的spider
  6. open_spider(spider) :能够在爬虫开启的时候执行一次
  7. close_spider(spider):能够在爬虫关闭的时候执行一次
  8. 上述俩个方法经常用于爬虫和数据库的交互,在爬虫开启的时候建立和数据库的连接,在爬虫关闭的时候断开和数据库的连接

三、编写位置

相关推荐
大叔是90后大叔10 天前
scrapy在pipelines中获取项目根目录
python·scrapy
_曦1 个月前
Scrapy如何设置iP,并实现IP重用, IP代理池重用
爬虫·scrapy
m0_748255261 个月前
【头歌】Scrapy爬虫(二)热门网站数据爬取
爬虫·scrapy
小白学大数据1 个月前
Django多线程爬虫:突破数据抓取瓶颈
数据库·爬虫·scrapy·数据分析·django
声声codeGrandMaster1 个月前
Scrapy中间件的使用
python·scrapy·中间件
蹦蹦跳跳真可爱5891 个月前
Python----Python爬虫(Scrapy的应用:CrawlSpider 使用,爬取小说,CrawlSpider版)
爬虫·python·scrapy
百年੭ ᐕ)੭*⁾⁾2 个月前
scrapy爬取图片
爬虫·python·scrapy
jidawanghao2 个月前
scrapy 教程
scrapy
后端常规开发人员2 个月前
Scrapy和Selenium结合使用完整步骤
python·selenium·scrapy
qq_375872692 个月前
16爬虫:使用requests和scrapy分别从链家获取二手房信息
爬虫·scrapy