• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

爬虫_020_scrapy_管道

武飞扬头像
唯念欢
帮助1

封装管道

        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文件中添加你需要爬取的数据类型】

  1.  
     
  2.  
    import scrapy
  3.  
     
  4.  
     
  5.  
    class DangdangwebItem(scrapy.Item):
  6.  
    # define the fields for your item here like:
  7.  
    # name = scrapy.Field()
  8.  
     
  9.  
    # 图片
  10.  
    img_src = scrapy.Field()
  11.  
    # 名字
  12.  
    name = scrapy.Field()
  13.  
    # 价格
  14.  
    price = scrapy.Field()

2.获取数据 

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

  1.  
    class DdwSpider(scrapy.Spider):
  2.  
    name = "ddw"
  3.  
    allowed_domains = ["category.dangdang.com"]
  4.  
    start_urls = ["http://category.dangdang.com/cp01.01.04.00.00.00.html"]
  5.  
     
  6.  
    # 下载第一页
  7.  
    def parse(self, response):
  8.  
    '''
  9.  
    pipelines --- 下载数据
  10.  
    items --- 定义数据结构
  11.  
    name_xpath: //a[@dd_name="单品图片"]/img/@alt
  12.  
    img_src_xpath: //a[@dd_name="单品图片"]/img/@src
  13.  
    price_xpath: //span[@class="search_now_price"]/text()
  14.  
    '''
  15.  
    li_list = response.xpath('//ul[@id="component_59"]/li')
  16.  
    for li in li_list:
  17.  
    # 因为第一张的图片地址并不在data-original中,而是再src中,所以这里需要做处理
  18.  
    img_src = li.xpath('.//img/@data-original').extract_first()
  19.  
    if img_src:
  20.  
    img_src = img_src
  21.  
    else:
  22.  
    img_src = li.xpath('.//img/@src').extract_first()
  23.  
    name = li.xpath('.//img/@al
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfibig
系列文章
更多 icon
同类精品
更多 icon
继续加载