Python爬虫入门-爬取LOL英雄信息写入txt文件

最新在学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.cn/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.cn/images/lol/act/img/js/hero/"+a+".js")
        get_sub("https://game.gtimg.cn/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()

最终效果如下:

我只是取了名字,物理伤害,魔法伤害,大图地址,头像地址等。其他的信息按照正则匹配逐个获取即可。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值