Scrapy爬虫,华为商城商品数据爬虫demo

来自于华为云开发者大会,使用Python爬虫抓取图片和文字实验,应用Scrapy框架进行数据抓取,保存应用了mysql数据库,实验采用的是线上服务器,而这里照抄全是本地进行,如有不同,那肯定是本渣渣瞎改了!

  • step1.配置环境

1.新建文件夹 huawei

2.命令行配置python虚拟环境

python -m venv ven

3.安装Scrapy框架

win7 64位系统下安装Scrapy框架 “pip install scrapy”,需要先安装相关环境,不然会报错,比如Twisted-,请自行对照python版本安装,本渣渣用的python3.8的所以下载的是Twisted-20.3.0-cp38-cp38-win_amd64.whl,没错,本渣渣是本地安装的方法安装的!

详细安装 win 安装Scrapy框架方法,推荐善用搜索引擎!

  • step2.创建Scrapy项目

同样的命令行操作

1.需要进入到指定目录,激活虚拟环境

cd huawei
env\Scripts\activate.bat

2.cmd命令行,新建Scrapy项目

scrapy startproject vmall_spider
cd vmall_spider
scrapy genspider -t crawl vmall "vmall.com"
  • step3.关键源码

1.vmall.py(核心爬取代码)

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from vmall_spider.items import VmallSpiderItem

class VamllSpider(CrawlSpider):    
 name = 'vmall'    
 allowed_domains = ['vmall.com']    
 start_urls = ['https://www.vmall.com/']    
 rules = (        
  Rule(LinkExtractor(allow=r'.*/product/.*'), callback='parse_item', follow=True),    
  )   

 def parse_item(self, response):
  title=response.xpath("//div[@class='product-meta']/h1/text()").get()     
  image=response.xpath("//a[@id='product-img']/img/@src").get()        
  item=VmallSpiderItem(
   title=title,
   image=image,
  )
  print("="*30)        
  print(title)
  print(image)        
  print("="*30)        
  yield item
    

2.items.py

import scrapy


class VmallSpiderItem(scrapy.Item):
    title=scrapy.Field()
    image=scrapy.Field()
    

3.pipelines.py

数据存储处理


import pymysql
import os
from urllib import request


class VmallSpiderPipeline:    
 def __init__(self):        
  dbparams={
      'host':'127.0.0.1', #云数据库弹性公网IP
      'port':3306, #云数据库端口            
      'user':'vmall', #云数据库用户
      'password':'123456', #云数据库RDS密码
      'database':'vmall', #数据库名称            
      'charset':'utf8'        
  }        
  self.conn=pymysql.connect(**dbparams)        
  self.cursor=self.conn.cursor()        
  self._sql=None

  self.path=os.path.join(os.path.dirname(os.path.dirname(__file__)),'images')        
  if not os.path.exists(self.path):            
   os.mkdir(self.path)    


 def process_item(self,item,spider):        
  url=item['image']        
  image_name=url.split('_')[-1]        
  print("--------------------------image_name-----------------------------")        
  print(image_name)        
  print(url)        
  request.urlretrieve(url,os.path.join(self.path,image_name))        
  self.cursor.execute(self.sql,(item['title'], item['image']))        
  self.conn.commit()        
  return item  
    

3.settings.py

更改的部分代码

BOT_NAME = 'vmall_spider'

SPIDER_MODULES = ['vmall_spider.spiders']
NEWSPIDER_MODULE = 'vmall_spider.spiders'

ROBOTSTXT_OBEY = False

DOWNLOAD_DELAY = 3

DEFAULT_REQUEST_HEADERS = {
 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',    
 'Accept-Language': 'en',    
 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',    
 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',    
 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16'
}

ITEM_PIPELINES = {
 'vmall_spider.pipelines.VmallSpiderPipeline': 300,
}

4.新建 start.py 运行调试入口文件

from scrapy import cmdline
cmdline.execute("scrapy crawl vmall".split())

  • step4.本地数据库配置

工具:phpstudy-面板(小皮面板)

链接工具:Navicat for MySQL

运行

来源:

使用Python爬虫抓取图片和文字实验

https://lab.huaweicloud.com/testdetail.html?testId=468&ticket=ST-1363346-YzykQhBcmiNeURp6pgL0ahIy-sso

关注本渣渣微信公众号:二爷记

      

后台回复关键字:“华为商城”

获取完整项目

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
数据技术体系图谱 演讲人 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
好的,您的问题是关于如何基于PythonScrapy、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') ``` 最终,您就可以运行分布式爬虫并抓取京东华为笔记本的数据了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值