人生苦短,快学Python!
今天是教使用大家selenium,一键爬取LOL英雄皮肤壁纸。
第一步,先要进行网页分析
一、网页分析
进入LOL官网后,鼠标悬停在游戏资料上,等出现窗口,选择资料库,点击进入。大家可以直接打开链接👉http://lol.qq.com/data/info-heros.shtml
进入了所有英雄的页面,随便选择一个英雄进行查看
检查可以发现一个一个名为hero_list.js的文件,里面保存了所有英雄的有关信息,可以将里面的内容复制下来保存到本地txt,然后再利用Python转为json。
import json # 读取txt里数据 with open('hreo_list.txt') as f: con = f.read() # 将str转换为json rep = json.loads(con) # 遍历 得到每个英雄的 ID print(f"有多少个英雄:{len(rep['hero'])}") # 有多少个英雄:152 # https://lol.qq.com/data/info-defail.shtml?id=876 count = 0 for item in rep['hero']: print(f"英雄ID:{item['heroId']}")
执行过程
依次点击英雄的详情页分析
id参数的值为.js文件中heroId对应的值 通过参数构造英雄详情页的URL 黑暗之女:https://lol.qq.com/data/info-defail.shtml?id=1 狂战士:https://lol.qq.com/data/info-defail.shtml?id=2 正义巨像:https://lol.qq.com/data/info-defail.shtml?id=3 含羞蓓蕾:https://lol.qq.com/data/info-defail.shtml?id=876
一些英雄的皮肤URL是规律的,比如安妮这样:
# big + id + 001.jpg 从001.jpg开始 https://game.gtimg.cn/images/lol/act/img/skin/big1001.jpg https://game.gtimg.cn/images/lol/act/img/skin/big1002.jpg https://game.gtimg.cn/images/lol/act/img/skin/big1003.jpg https://game.gtimg.cn/images/lol/act/img/skin/big1004.jpg https://game.gtimg.cn/images/lol/act/img/skin/big1005.jpg
但有些又像派克这样,皮肤URL不规律
https://game.gtimg.cn/images/lol/act/img/skin/big555001.jpg # 第一张 https://game.gtimg.cn/images/lol/act/img/skin/big555009.jpg # 第二张 https://game.gtimg.cn/images/lol/act/img/skin/big555016.jpg # 第三张00000000000000
这样的情况,构造URL来请求下载图片不方便,我们直接上 selenium 大法👇
二、selenium爬虫
爬虫大法好,走起🚀
部分爬虫代码,完整代码下载见文末👇
def create_urls(): # 读取txt里数据 with open('hreo_list.txt') as f: con = f.read() # 将str转换为json rep = json.loads(con) # 遍历 得到每个英雄的 ID print(f"有多少个英雄:{len(rep['hero'])}") # https://lol.qq.com/data/info-defail.shtml?id=876 id_ = [] for item in rep['hero']: # print(f"英雄ID:{item['heroId']} -- 英雄名称:{item['name']}") id_.append((item['heroId'],item['name'])) return id_
运行效果如下:
预览结果
死亡如风,常伴吾身。吾虽浪迹天涯,却未迷失本心。长路漫漫,唯剑作伴。
想当初,我的亚索也是很快乐的~
近期有很多朋友通过私信咨询有关Python学习问题。为便于交流,点击蓝色自己加入讨论解答资源基地