scrapy爬取华为商城所有商品信息--科技快人一步

华为商城 https://www.vmall.com/index.html

目标:华为商城下的商品信息
  • 按主页的左边手机,笔记本&平板,智能穿戴……分类
  • 每一个分类下的小分类
    • 商品标题
    • 商品价格
  • 规格参数
    • 主要参数
    • 主体
    • ……
    • 商品编码
  • 写入excel
  • 设置好excel数据表,分析数据

代码如下(scrapy):

# -*- coding: utf-8 -*-
import os
import re
import urllib.request
from copy import deepcopy

import scrapy
import xlrd
import xlwt
from ..items import HuaweiItem


class HuaWei(scrapy.Spider):
    name = 'huawei'
    allowed_domains = ['vmall.com', 'vmallres.com']
    start_urls = ['http://vmall.com/']

    def parse(self, response):
        self.new_xls()
        # 主页
        print("分割线-----------------------主页------------------------分割线")
        classify_list_A = response.xpath('//div[@id="category-block"]/div/ol/li')
        print("大分类长度:", len(classify_list_A))
        for i in classify_list_A:
            # print("现在位置:", classify_list_A)
            item = HuaweiItem()
            item['classify_A'] = i.xpath('.//input[2]/@value').extract_first()
            classify_list = i.xpath('.//div[2]//li[not(@class="subcate-btn")]')
            # classify_list = i.xpath('.//div[2]//li[last()]')
            for i in classify_list:
                item['classify_B'] = i.xpath('.//input[1]/@value').extract_first()
                href = "https://www.vmall.com" + str(i.xpath('.//a/@href').extract_first()) + '-1-3-0'
                # print("href:", href)
                yield scrapy.Request(
                    href,
                    callback=self.parse_A,
                    meta={"item": deepcopy(item)}
                )
        rb = xlrd.open_workbook('华为商城.xls')
        # 通过sheet_by_index()获取的sheet
        rs = rb.sheet_by_index(0)
        print("已爬取的商品数量:", rs.nrows - 1)

    def parse_A(self, response):
        # 中间页
        print("分割线-----------------------中间页------------------------分割线")
        li_list = response.xpath('//div[@class="layout"]/div[@class="channel-list"]/div[@class="pro-list clearfix"]/ul/li')
        if li_list:
            print("正在爬取页面链接:", response.request.url)
            print("此页面商品数量:", len(li_list))
            for i in li_list:
                item = response.meta["item"]
                rb = xlrd.open_workbook('华为商城.xls')
                # 通过sheet_by_index()获取的sheet
                rs = rb.sheet_by_index(0)
                cods = rs.col_values(0, start_rowx=0, end_rowx=None)
                item['title'] = i.xpath('./div[1]/p[2]/a/span[1]/text()').extract_first()
                # print("+++++++++++++++++++++++++++++++++++++++++++", item['title'])
                item['price'] = round(float(i.xpath('./div[1]/p[3]/b/text()').extract_first().split("¥")[1]) if i.xpath('./div[1]/p[3]/b/text()') else 0, 2)
                item['comments'] = int(i.xpath('./div[1]/div[@class="p-button clearfix"]//label//text()').extract_first().split("人")[0])
                item['img'] = i.xpath('./div[1]/p[1]/a/img/@src').extract_first()
                item['href'] = "https://www.vmall.com" + i.xpath('./div[1]/p[1]/a/@href').extract_first()
                item['coding'] = re.findall('[(]\'(.*?)\'[)]', i.xpath('./div[1]/p[1]/a/@onclick').extract_first())
                # for s in cods:
                #     if s == item['coding']:
                #         break
                # print(cods)
                # print(item['coding'])
                if item['coding'][0] not in cods:
                    yield scrapy.Request(
                        item['href'],
                        callback=self.parse_B,
                        meta={"item": deepcopy(item)}
                    )
            next_url_len = len(response.xpath('//ul[@id="page_ul"]/a'))
            # print("::::::::::::::::::::::::;;", next_url_len)
            if int(response.request.url.split("-")[2]) < next_url_len:
                href = response.request.url.split("-")[0] + "-" + response.request.url.split("-")[1] + "-" + str(
                    int(response.request.url.split("-")[2]) + 1) + '-3-0'
                print("next_href:", href)
                yield scrapy.Request(
                    href,
                    callback=self.parse_A,
                    meta={"item": deepcopy(item)}
                )


    def parse_B(self, response):
        # 详情页
        print("分割线-----------------------详情页------------------------分割线")
        item = response.meta["item"]
        print("现在位置%s/%s" % (item["classify_A"], item["classify_B"]))
        print("正在爬取:", item['title'])
        content = response.xpath('//div[@id="product-property-recommand"]')
        if content:
            item['promotion'] = self.get_cx(response)
            item['coding'] = content.xpath(
                './div[@class="product-description clearfix"]/div[@class="fl"]/text()').extract_first().strip()
            item['explain'] = content.xpath('.//div[@id="skuPromWord"]//span/text()').extract_first()
            server_explain = content.xpath(
                './/div[@id="product-pulldown1"]/div[1]/div[@class="product-description-list clearfix"]/ul/li')
            item['server_explain'] = self.get_cm(server_explain)
            item['content'] = content.xpath('.//h1[@id="pro-name"]/text()').extract_first()
            cu_1 = re.findall(r'<script src="(.*?)" namespace="ec"></script>', response.text)[1]
            yield scrapy.Request(
                cu_1,
                callback=self.get_cu_1,
                meta={"item": deepcopy(item)},
                dont_filter=True
            )
        else:
            content = response.xpath('//div[@class="pro-meta-area"]')
            item['content'] = content.xpath('.//h1[@id="pro-name"]/text()').extract_first()
            item['explain'] = content.xpath('.//div[@id="skuPromWord"]//span/text()').extract_first()
            item['server_explain'] = content.xpath('.//div[@class="pro-service"]/text()').extract_first()
            item['promotion'] = "暂无活动"
            yield item

    def get_cx(self, response):
        print("获取促销")
        """获取促销数据"""
        str = ""
        cu = re.findall(r'_groupPhotoList.push[(]{name:.*?}[)]; (_promotionsList+.*?); _prolongLst.push', response.text)
        # print(cu)
        if cu:
            try:
                cs = re.findall(r'"(.*?)"', cu[1])
            except:
                cs = re.findall(r'"(.*?)"', cu[0])
                print(cu)
                print(len(cu))
            # print(cs)
            index = 0
            pop_list = []
            for i in cs:
                # 遍历促销,去掉没用的数据
                # print("开始", index)
                i = i.replace(r'&#x2f', "/")
                if i.find('&#x') != -1:
                    i = i.replace("&#x", "\\u")
                    i = i.replace(";", "")
                    i = i.replace("\n", "")
                    i = i.replace("\t", "")
                    i = i.replace(" ", "")
                    i = i.encode().decode('unicode-escape')
                    cs[index] = i
                else:
                    # print("添加了:", index)
                    pop_list.append(index)
                index += 1
                # print("结束")
            for i in pop_list[::-1]:
                cs.pop(i)
            ins = 0
            for i in cs:
                # print("index:", cs.index(i))
                str += i
                ins += 1
                if ins % 2 is 0:
                    str += ";"
                elif ins % 2 is 1:
                    str += ":"
        return str
        # cu_1 = re.findall(r'<script src="(.*?)" namespace="ec"></script>', response.text)[1]
        # print(cu_1)
        # yield scrapy.Request(
        #     cu_1,
        #     callback=self.get_cu_1,
        #     meta={"item": item, "str": str}
        # )
        # req = urllib.request.urlopen(cu_1)
        # req = req.read()
        # req = req.decode("utf-8")
        # str += self.get_cu_1(req)
        # print("str_s", str)
        # return str
        # item['promotion'] = str

        # print("cu_1", cu_1)
        # scrapy.Request(
        #     cu_1,
        #     callback=self.get_cu_1,
        #     meta={"item": item}
        # )
        # print(rs)
        #
        # return str
        # yield scrapy.Request(
        #     cu_1,
        #     callback=self.get_cu_1,
        #     meta={"item": item, "str": str}
        # )

    def get_cu_1(self, response):
        #获取促销(购买可的积分)
        print("进入GET_CU_1")
        item = response.meta["item"]
        print(item)
        cu1 = re.findall(r' \\x3e\'[)],a.push[(](.*?")[)],', response.text)[0]
        cul_1 = re.findall(r'\\x3e(.*?)\\x3c', cu1)[0].encode().decode('unicode-escape')
        cul_2 = re.findall(r'a.push[(]"(.*?)"', cu1)[0].encode().decode('unicode-escape')
        str = cul_1 + ":" + cul_2 + ";"
        print("--------------------------str----------------------------------")
        item['promotion'] += str
        if item['promotion'] is '':
            item['promotion'] = "暂无活动"
        yield item
        # self.get_cu_1(self)



    def new_xls(self):
        """创建表格"""
        if not os.path.exists("华为商城.xls"):
            print("正在创建。。。")
            wb = xlwt.Workbook(encoding='utf-8')
            # 括号内参数为表名
            ws = wb.add_sheet('商品数据')
            # 参数1:行数
            # 参数2:列数 从0开始计数
            # 参数3:值   即单元格的内容
            ws.write(0, 0, label='商品编码')
            ws.write(0, 1, label='祖分类')
            ws.write(0, 2, label='父分类')
            ws.write(0, 3, label='标题')
            ws.write(0, 4, label='图片')
            ws.write(0, 5, label='链接')
            ws.write(0, 6, label='价格')
            ws.write(0, 7, label='评价数量')
            ws.write(0, 8, label='内容')
            ws.write(0, 9, label='说明')
            ws.write(0, 10, label='服务说明')
            ws.write(0, 11, label="促销")
            wb.save('华为商城.xls')

    def get_cm(self, server_explain):
        # 获取服务说明
        cm = ""
        for i in server_explain:
            text = i.xpath('./text()')
            if len(text) > 1:
                mm = ""
                str_1 = re.findall(r'data=\'(.+?)\'>', str(text))
                if i.xpath('./span/text()'):
                    for k in str_1:
                        mm += k
                        if str_1.index(k) == 0:
                            mm += i.xpath('./span/text()').extract_first()
                cm += mm
            else:
                cm += str(text.extract_first()) + ';'

        return cm

git地址

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
大数据技术体系图谱 演讲人 2021-08-08 大数据技术体系图谱全文共96页,当前为第1页。 目录 01. 数据采集 07. 数据应用 03. 数据存储 05. 基础技术 02. 数据传输 04. 数据处理 06. 数据治理 大数据技术体系图谱全文共96页,当前为第2页。 01 数据采集 大数据技术体系图谱全文共96页,当前为第3页。 日志采集 埋点 PC 打点 移动端打点 服务端打点 采集框架 Logstash Flume Fluentd Chukwa 大数据技 体系图谱全文共96页,当前为第4页。 外部数据 网络数据采集 文本 图片 视频 虫技术 Nutch Heritrix Scrapy WebCollector 大数据技术体系图谱全文共96页,当前为第5页。 数据采集 IoT设备 传感器 探针 大数据技术体系图谱全文共96页,当前为第6页。 02 数据传输 大数据技术体系图谱全文共96页,当前为第7页。 数据传输 消息队列 数据同步 数据订阅 序列化 大数据技术体系图谱全文共96页,当前为第8页。 数据传输 消息队列 Kafka ActiveMQ RabbitMQ RocketMQ ZeroMQ 5. 4. 3. 2. 1. 大数据技术体系图谱全文共96页,当前为第9页。 数据传输 数据同步 DataX Kettle Cannal Sqoop SymmetricDS OGG(Oracle Golden Gate) 大数据技术体系图谱全文共96页,当前为第10页。 数据传输 数据订阅 Databus 01 Wormhole 03 Otter 02 阿里云 DTS 04 大数据技术体系图谱全文共96页,当前为第11页。 数据传输 序列化 JSON 01 Protobuf 02 Hessian 03 FST 04 MessagePack 05 Avro 06 大数据技术体系图谱全文共96页,当前为第12页。 序列化 数据传输 Kryo 大数据技术体系图谱全文共96页,当前为第13页。 03 数据存储 大数据技术体系图谱全文共96页,当前为第14页。 数据存储 分布式文件/对象存储 02 物理存储 01 分布式关系型数据库 03 分析型数据库 04 搜索引擎 05 K-V存储 06 大数据技术体系图谱全文共96页,当前为第15页。 数据存储 图数据库 列存储数据库 文档数据库 时序数据库 大数据技术体系图谱全文共96页,当前为第16页。 数据存储 物理存储 主流框架 01 存储类型 02 大数据技术体系图谱全文共96页,当前为第17页。 直连式存储(DAS:Direct-Attached Storage) 网络化存储(FAS:Fabric-Attached Storage) 网络接入存储(NAS:Network-Attached Storage) 存储区域网络(SAN:Storage Area Network) 主流框架 大数据技术体系图谱全文共96页,当前为第18页。 块存储 磁盘阵列 DAS SAN 文件存储 FTP NFS NAS 对象存储 存储类型 大数据技术体系图谱全文共96页,当前为第19页。 数据存储 分布式文件/对象存储 COS(腾讯云) 02 OSS(阿里云) 01 OBS(华为云) 03 KODO(七牛云) 04 UFile(UCloud) 05 HDFS 06 大数据技术体系图谱全文共96页,当前为第20页。 数据存储 分布式文件/对象存储 Ceph 02 Open Stack Swift 01 GlasterFS 03 Facebook Hasystack 04 Lustre 05 AFS 06 大数据技术体系图谱全文共96页,当前为第21页。 OSS(阿里云) 01 06 UFile(UCloud) 03 KODO(七牛云) OBS(华为云) HDFS 02 COS(腾讯云) 04 05 分布式文件/对象存储 单击此处添加文本具体内容,简明扼要的阐述您的观点。根据需要可酌情增减文字,以便观者准确的理解您传达的思想。 单击此处添加标题 大数据技术体系图谱全文共96页,当前为第22页。 分布式文件/对象存储 Ceph 02 Open Stack Swift 01 GlasterFS 03 Facebook Hasystack 04 Lustre 05 AFS 06 大数据技术体系图谱全文共96页,当前为第23页。 数据存储 分布式关系型数据库 DRDS TiDB Cobar Mycat Aurora 5. 4. 3. 2. 1. 大数据技术体系图谱全文共96页,当前为第24页。 分布式关系型数据库 DRDS TiDB Cobar Mycat Aurora 大数据技术体系图谱全文共96页,当前为第25
好的,您的问题是关于如何基于Python、Scrapy、Redis和Rule组件实现分布式京东华为笔记本的。首先,您需要安装Scrapy和Redis,并在Scrapy的配置文件中添加Redis相关的配置: ```python # 在settings.py中添加以下配置 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" SCHEDULER = "scrapy_redis.scheduler.Scheduler" SCHEDULER_PERSIST = True REDIS_URL = 'redis://localhost:6379' ``` 然后,您需要编写Spider和Item Pipeline,其中Spider负责解析并抓网页,Item Pipeline负责处理抓到的数据。下面是一个示例的Spider代码: ```python from scrapy_redis.spiders import RedisSpider from scrapy.selector import Selector from ..items import ProductItem class JdSpider(RedisSpider): name = 'jd' redis_key = 'jd:start_urls' def parse(self, response): sel = Selector(response) products = sel.xpath('//div[@class="gl-i-wrap"]') for product in products: item = ProductItem() item['name'] = product.xpath('div[@class="p-name"]/a/em/text()').extract_first() item['price'] = product.xpath('div[@class="p-price"]/strong/i/text()').extract_first() item['url'] = product.xpath('div[@class="p-name"]/a/@href').extract_first() yield item ``` 在Item Pipeline中,您可以对抓到的数据进行清洗和存储,下面是一个示例的Item Pipeline代码: ```python import pymongo class JdPipeline(object): def __init__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DATABASE', 'items') ) def open_spider(self, spider): self.client = pymongo.MongoClient(self.mongo_uri) self.db = self.client[self.mongo_db] def close_spider(self, spider): self.client.close() def process_item(self, item, spider): self.db['products'].insert(dict(item)) return item ``` 最后,您需要创建一个Redis队列,并向队列中添加起始URL,如下所示: ```python import redis r = redis.Redis(host='localhost', port=6379) r.lpush('jd:start_urls', 'https://search.jd.com/Search?keyword=%E5%8D%8E%E4%B8%BA%E7%AC%94%E8%AE%B0%E6%9C%AC&enc=utf-8') ``` 最终,您就可以运行分布式虫并抓京东华为笔记本的数据了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值