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
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
好的,您的问题是关于如何基于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、付费专栏及课程。

余额充值