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. 上述俩个方法经常用于爬虫和数据库的交互,在爬虫开启的时候建立和数据库的连接,在爬虫关闭的时候断开和数据库的连接

三、编写位置

相关推荐
养乐多q.♡15 小时前
scrcpy 设置手机熄屏后不影响投屏
scrapy·智能手机·手机控制
韩立学长3 天前
【开题答辩实录分享】以《计算机类专业招聘信息爬取与查询系统设计与实现》为例进行答辩实录分享
python·scrapy·django
Aerelin3 天前
scrapy的介绍与使用
前端·爬虫·python·scrapy·js
生而为虫3 天前
31.Python语言进阶
python·scrapy·django·flask·fastapi·pygame·tornado
m***66734 天前
网页数据抓取:融合BeautifulSoup和Scrapy的高级爬虫技术
爬虫·scrapy·beautifulsoup
猫头虎5 天前
如何解决pip install网络报错SSLError: TLSV1_ALERT_PROTOCOL_VERSION(OpenSSL过旧)问题
网络·python·scrapy·pycharm·beautifulsoup·pip·scipy
桃子叔叔6 天前
爬虫实战|Scrapy+Selenium 批量爬取汽车之家海量车型外观图(附完整源码)一
爬虫·selenium·scrapy
深蓝电商API6 天前
Scrapy + Scrapy-Redis 分布式爬虫集群部署(2025 最新版)
redis·分布式·scrapy
深蓝电商API7 天前
爬虫界的 “核武器”:Splash + Scrapy 动态渲染终极方案
爬虫·scrapy·splash
m***667314 天前
【爬虫】使用 Scrapy 框架爬取豆瓣电影 Top 250 数据的完整教程
爬虫·scrapy