scrapy数据爬取和数据处理

scrapy把爬取数据和处理数据分别放在以下两个位置(itcast为我们创建的爬虫名)
在这里插入图片描述在这里插入图片描述
数据爬取的代码如下(其中parse方法中的response是请求start_urls的返回):

import scrapy


class ItcastSpider(scrapy.Spider):
    name = 'itcast' #爬虫名字
    allowed_domains = ['itcast.cn'] #爬取范围
    start_urls = ['http://www.itcast.cn/channel/teacher.shtml?jingjiaczpz-PC-1'] #爬取url

    # 对url响应的处理
    def parse(self, response):
        #print(response.xpath("//div[@class='tea_con']/div/ul/li/h3/text()"))
        #extract返回的是一个类似于list
        #res = response.xpath("//div[@class='tea_con']/div/ul/li//h3/text()").extract()
        li_list=response.xpath("//div[@class='tea_con']/div/ul/li")
        for li in li_list:
            item={}
            #extract_first返回的是第一个字符串,如果为空,就返回None
            item["name"]=li.xpath(".//h3/text()").extract_first()
            item["level"]=li.xpath(".//h4/text()").extract_first()
            item["desc"]=li.xpath(".//p/text()").extract_first()
            yield item#使用yield方便数据处理,且只能yield dic、None、Request、BaseItem
 


接下来就是数据处理:

首先我们要在配置文件中打开

ITEM_PIPELINES = {
   'mySpider.pipelines.MyspiderPipeline': 300,
    'mySpider.pipelines.MyspiderPipeline1': 301,
}

其中键为管道的地址,值为管道离引擎的距离,距离越小,越优先执行

接下来在管道中进行数据处理

class MyspiderPipeline:
    def process_item(self, item, spider):
        if spider.name=="itcast":
            print(item)
        
        return item
class MyspiderPipeline1:
    def process_item(self, item, spider):
        if spider.name == "itcast":
            print(item)
    
        return item

process_item()方法中的item即为yield的内容,spider为这个item是哪个爬虫的,所以我们可以对不同的爬虫采取不同的处理。
因为第一个管道的距离小于第二个 所以先执行第一个,在字典中添加一个a属性,然后第二个管道进行输出(注意:当后一个管道需要使用前一个管道的结果时,前一个管道需要return)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值