爬虫_020_scrapy_管道

封装管道

        1.在items文件中定义结构数据

        2.在爬虫文件中获取数据并将其通过yield方法交给管道【pipelines】

        3.开启管道【settings中取消ITEM_PIPELINES 的注释】

        4.在管道中定义两个函数【open_spider(self, spide)、close_spider(self, spider)】

这两个函数中,open放在主体函数process_item之前,close放在之后

1. items -- 定义结构数据【就是在items文件中添加你需要爬取的数据类型】


import scrapy


class DangdangwebItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()

    # 图片
    img_src = scrapy.Field()
    # 名字
    name = scrapy.Field()
    # 价格
    price = scrapy.Field()

2.获取数据 

 在scrapy中可以在xpth给出的数据后再使用xpath【当当网案例】

class DdwSpider(scrapy.Spider):
    name = "ddw"
    allowed_domains = ["category.dangdang.com"]
    start_urls = ["http://category.dangdang.com/cp01.01.04.00.00.00.html"]

#   下载第一页
    def parse(self, response):
        '''
        pipelines --- 下载数据
        items --- 定义数据结构
        name_xpath: //a[@dd_name="单品图片"]/img/@alt
        img_src_xpath: //a[@dd_name="单品图片"]/img/@src
        price_xpath: //span[@class="search_now_price"]/text()
        '''
        li_list = response.xpath('//ul[@id="component_59"]/li')
        for li in li_list:
            # 因为第一张的图片地址并不在data-original中,而是再src中,所以这里需要做处理
            img_src = li.xpath('.//img/@data-original').extract_first()
            if img_src:
                img_src = img_src
            else:
                img_src = li.xpath('.//img/@src').extract_first()
            name = li.xpath('.//img/@al
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值