作者:葉庭雲、朱小五
來源:快學Python
人生苦短,快學Python!
今天是教使用大家selenium,一鍵爬取LOL英雄皮膚桌面。
第一步,先要進行網頁分析
一、網頁分析
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAjM2EzLcd3LcJzLcJzdllmVldWYtl2Pn5GcuMTYjFWOwQTNygjN3UDMhBjMidDMhNGZ4IDMzIDO3kDZvwVMxkjM4QzNtUGall3LcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.png)
進入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_
複制
運作效果如下:
預覽結果
死亡如風,常伴吾身。吾雖浪迹天涯,卻未迷失本心。長路漫漫,唯劍作伴。
想當初,我的亞索也是很快樂的~