admin管理员组文章数量:1619183
最新在学es,搭建完后要搞点数据进去测测。
正好爱玩LOL,用python爬取LOL官网中英雄信息,先写入txt文件,后面要写库或者啥的用熟悉的java处理。
因为不是专业搞python的,具体python语法就不详细讲了,安装完环境,用代码直接跑就行了,报什么错下什么包就行了。
后面要爬其他的,根据这个改改代码基本就行了。
首先到LOL官网,英雄资料库地址;分析,具体的英雄id都在hero_list.js中。
可以看到,这个js里面基本上包含了所有的英雄id的信息
第一步,正则匹配获取所有英雄id;
第二步,查看英雄的详情页,点击英雄头像进去,会发现请求英雄id.js这个资源。
这个里面基本上包含了所有的英雄详情信息,也就是我们的最终目标;遍历上面的id请求,然后匹配出自己需要的信息。
完整代码:
from bs4 import BeautifulSoup
from selenium import webdriver
import requests
import time
import re
import json
def get_html():
url = 'https://game.gtimg/images/lol/act/img/js/heroList/hero_list.js'
strhtml = requests.get(url)
file_handle = open('2.txt', mode='w')
a_labels = re.findall('{"heroId":"(.*?)","n', strhtml.text)
for a in a_labels:
print("https://game.gtimg/images/lol/act/img/js/hero/"+a+".js")
get_sub("https://game.gtimg/images/lol/act/img/js/hero/" +
a+".js", file_handle)
file_handle.close()
def get_sub(subhtml, filehandle):
strhtml = requests.get(subhtml)
strhtml.encoding = 'utf-8'
bf = BeautifulSoup(strhtml.text)
pagehtml = bf.encode('utf-8').decode('unicode_escape')
name = re.findall('"name":"(.*?)","alias', pagehtml)
alias = re.findall('"alias":"(.*?)","title', pagehtml)
roles = re.findall('"title":"(.*?)","roles', pagehtml)
attack = re.findall('"attack":"(.*?)","defense', pagehtml)
magic = re.findall('"magic":"(.*?)","difficulty', pagehtml)
iconImg = re.findall('"iconImg":"(.*?)","loadingImg', pagehtml)
mainImg = re.findall('"mainImg":"(.*?)","iconImg', pagehtml)
result = (name[0]+'\t'+alias[0]+'\t'+roles[0]+'\t'+attack[0]+'\t'+magic[0]+'\t'+iconImg[0] +
'\t'+mainImg[0]+'\n')
print(name[0]+'\t'+alias[0]+'\t'+roles[0]+'\t'+attack[0]+'\t'+magic[0]+'\t'+iconImg[0] +
'\t'+mainImg[0])
filehandle.writelines(result)
if __name__ == '__main__':
html = get_html()
最终效果如下:
我只是取了名字,物理伤害,魔法伤害,大图地址,头像地址等。其他的信息按照正则匹配逐个获取即可。
版权声明:本文标题:Python爬虫入门-爬取LOL英雄信息写入txt文件 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1728793273a1173923.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论