对python爬虫中scrapy框架代码学习理解

         经过对scrapy框架的简单学习后,对其编码过程进行如下简单的梳理,以便于自己今后的复习。与大多数爬虫编写过程基本一致,主要过程如下:

       1、首先创建工程文件:scrapy  startproject   xxxPro

                   通过cd进入工程文件:     cd  xxxPro

                通过scrapy  genspider    XXX  www.xxx.com创建爬虫文件XXX,

       2、创建好爬虫文件后,注释掉#allowed_domains = ['www.xxx.com']

       3、利用 def parse(self, response)  封装好的response,结合xpath对需要爬取的数据内容进行对应的数据解析,以上步骤编码如下:

import scrapy
class TupianSpider(scrapy.Spider):
    name = 'tupian'
    #allowed_domains = ['www.xxx.com']
    start_urls = ['http://www.sccnn.com/sheyingtuku/renwuqinggan/20221004-301271.html']

    def parse(self, response):
     src=response.xpath('//[@id="LeftBox"]/div[1]/div/font/img/@src').extract_first()
   Name = response.xpath('//*[@id="LeftBox"]/div[1]/h2/text()').extract_first()
    print(src,Name)

 解析好的内容提取时,须用到.extract()方法

     4、数据的持久化存储

              1)、基于终端指令的数据持久化存储,此方法使用较少不推荐,以编码做简单记录

def parse(self, response):
    src = response.xpath('//*[@id="LeftBox"]/div[1]/div/font/img/@src').extract_first()
    Name = response.xpath('//*[@id="LeftBox"]/div[1]/h2/text()').extract_first()
    #print(src,Name)
    #先添加一个字典,然后将字典加装到列表当中。同时通过return进行返回(这一步具体操作视情况使用)
    dict = {
        'src':src,
        'Name':Name
    }
    img.append(dict)
    return img
       2)、基于管道的数据持久化存储,这里主要需使用到items.py和piplines.py
 基于管道的数据持久化存储,分为3步:
      一、实例化item对象,步骤为:
       items.py   步骤一:
class TupianproItem(scrapy.Item):
    # define the fields for your item here like:
    src = scrapy.Field()
    Name = scrapy.Field()
    pass
步骤二:这里需要在爬虫文件里进行导包:from  tupianPro.items  import  TupianproItem
   def parse(self, response):
    src = response.xpath('//*[@id="LeftBox"]/div[1]/div/font/img/@src').extract_first()
    Name = response.xpath('//*[@id="LeftBox"]/div[1]/h2/text()').extract_first()
    # print(src,Name)
    item = TupianproItem()
    item['src']=src
    item['Name']=Name
    yield item #通过yield上传给管道
  二、piplines.py管道接收item对象,同时编写本地保存路径,具体编码过程如下:# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class TupianproPipeline:
    fp = None
    #重写父类的一个方法:该方法只在开始爬虫的时候被调用一次
    #此方法可理解为创建文件夹的第二种方法
    def open_spider(self,spider):
        self.fp = open('./tupian.txt','w',encoding='utf-8')
    #专门用来处理item类型对象
    #该方法可以接收爬虫文件提交过来的item对象
    #该方法每接收一个item对象就会被调用一次
    def process_item(self, item, spider):
        src = item['src']
        Name = item['Name']
        self.fp.write(src+':'+Name+'\n')
        return item
    def close_spider(self,spider):
        print('结束爬虫!!!')
        fp.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值