Python爬取王者荣耀所有英雄以及高清大图

爬虫的原理:

  • 模拟浏览器的行为,通过网络请求将目标网页抓取到本地。
  • 使用一定的匹配规则,将目标网页中需要的数据提取出来,把不需要的过滤掉。
  • 根据需求,把提取出来的数据存储到磁盘中(json、csv、excel、数据库)。

需要安装的库:

  • requests:用来做网络请求的。就跟浏览器是一样的。安装方式:
    pip install requests
    
  • bs4:用来将请求下来的数据进行解析的。安装方式:
    pip install bs4
    
  • lxml:这个库是用来解析html和xml格式数据的。BeautifulSoup相当于只是一个壳,底层还是要基于lxml类似的这种解析器来解析。html5lib、html.parse。也要安装。安装方式如下:
    pip install lxml
    

王者荣耀的英雄列表
https://pvp.qq.com/web201605/herolist.shtml
官网部分展示图:

Python爬取王者荣耀所有英雄以及高清大图

点击头像进去如下:
看下黄忠


Python爬取王者荣耀所有英雄以及高清大图

我要获取的就是王者荣耀现在所有的88个英雄以及详情页英雄的皮肤,还有高清图片。

废话不多说,搞起!!!!

首先,搞定开头说的前两步,请求网络和提取数据!

headers = {
     "user-agent": '"你自己的user-agent"
 }
 url =“抓取网页的目标url”
 requestResult = requests.get(url, headers=headers)

 resultJson = json.loads(requestResult.text)
 print(type(resultJson))
 heros = []

 for li in resultJson:
     hero = {}
     hero['ename'] = li['ename']
     hero['cname'] = li['cname']
     hero['skin_name'] = li['skin_name']
     hero['skin_name'] = str(hero['skin_name']).split('|')[::-1]

     _ename = str(hero['ename'])

     index = 1
     smallImages = []
     bigImages = []
     # 获取某个英雄的所有皮肤和高清大图
     for item in hero['skin_name']:
         # url是分析得出,并且需要拼接好
         singleSmallImage ='某个英雄的所有皮肤中的相对应的一个url‘
         smallImages.append(singleSmallImage)
         singleBigImage =‘某个英雄的高清皮肤中的相对应的一个url'
         bigImages.append(singleBigImage)

         hero['smallimages'] = smallImages
         hero['bigimages'] = bigImages
         index = index + 1
     _imgurl = '这个是英雄默认皮肤的url'
     hero['img'] = _imgurl
     heros.append(hero)

     heroTag = {'totalhero': heros}

上面用到的需要导入

import requests

我这里不需要Dom树形结构,没有用到BeautifulSoup

最后保存数据,这里保存为hero_json.json文件

 with open('hero_json.json', 'w', encoding='utf-8') as fp:
        json.dump(data, fp, ensure_ascii=False)
    return 'ok'

hero_json.json文件整理:


Python爬取王者荣耀所有英雄以及高清大图

赵云的数据

Python爬取王者荣耀所有英雄以及高清大图

bigimages中的最后一条数据为赵云的“引擎之心”高清皮肤

Python爬取王者荣耀所有英雄以及高清大图

smallimages为赵云的七款皮肤小图,不看了。

手机上的效果:


Python爬取王者荣耀所有英雄以及高清大图
Python爬取王者荣耀所有英雄以及高清大图

这里遇到坑了,最开始获取的所有英雄的列表数据是没有的,最后才看到是通过JavaScript实现的动态展示。

此文用作学习,以此记录!!!

如果此文对您有帮助,请点个赞让更多的人看到!