本人博客:https://xiaoxiablogs.top

此次爬取lol英雄皮肤一共有两个版本,分别是多线程版本和非多线程版本。

多线程版本

# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2/25/2020 2:24 PM
# @Author : XiaoXia
# @Blog : https://xiaoxiablogs.top
# @File : lol_hero_photo.py
import datetime import requests
import simplejson
import os
import threading # 多线程版本
class HeroImage(threading.Thread):
# lol英雄获取英雄皮肤列表网站
url_demo = "https://game.gtimg.cn/images/lol/act/img/js/hero/"
# 设置ua
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36"
headers = {
'User-Agent': ua
} def __init__(self, hero_id, hero_name):
threading.Thread.__init__(self)
self.hero_id = hero_id
self.hero_name = hero_name.replace("/", "") def run(self):
print("{}的皮肤爬取开始了!!!".format(self.hero_name))
hero_images_list = self.getImagesUrl()
self.dirIsExist()
for hero_images in hero_images_list:
self.saveImage(hero_images["url"], hero_images['name'].replace("/", ""))
print("{}皮肤爬取完成!!!".format(self.hero_name)) def dirIsExist(self):
"""
判断文件夹是否存在,不存在则创建
"""
if not os.path.exists("./hero/"):
os.mkdir("./hero/")
path = "./hero/{}/".format(self.hero_name)
if not os.path.exists(path):
os.mkdir(path) def getImagesUrl(self) -> list:
"""
获取皮肤照片链接
:return: 皮肤照片数组
"""
response = self.getJson(self.url_demo + self.hero_id + ".js")
images = simplejson.loads(response.text)['skins']
image_list = []
'''
skinId: 图片的编号
name: 皮肤名称
mainImg: 图片地址
'''
for image in images:
image_dic = {
"name": image['name'],
"url": image['mainImg']
}
# 由于其中还有一些炫彩模型,所以要去除掉
if image_dic['url']:
image_list.append(image_dic) return image_list def saveImage(self, url: str, image_name: str):
"""
通过链接获取图片并且将图片保存到相应的目录下
:param path: 保存目录
:param image_name: 图片名称
:param url: 图片地址
"""
response = requests.get(url, headers=self.headers)
image_path = "./hero/{}/{}.jpg".format(self.hero_name, image_name) with response:
# 得到图片的二进制文件
image_file = response.content
with open(image_path, "wb+") as f:
f.write(image_file)
f.flush() @staticmethod
def getJson(hero_url: str) -> requests.models.Response:
"""
获取json响应
:param hero_url: 英雄列表的获取链接
:return:
"""
response = requests.get(hero_url, headers=HeroImage.headers)
return response if __name__ == "__main__":
# 用于计算程序运行时间的,不需要可直接删除该语句
start_time = datetime.datetime.now()
# lol英雄列表
hero_list = "https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js"
jsons = HeroImage.getJson(hero_list)
heros = simplejson.loads(jsons.text)["hero"]
for hero in heros:
'''
编号: heroId
称号: name
英文名: alias
中文名: title
'''
name = hero['name'] + '-' + hero['title'] name = name.replace("/", "")
thread = HeroImage(hero['heroId'], name)
thread.start()
print(threading.active_count())
# 用于计算程序运行时间的,不需要可直接删除该循环
while True:
if threading.active_count() <= 1:
print("全部爬取完毕")
end_time = datetime.datetime.now()
print("总用时为:", end_time-start_time)
break

非多线程版本

# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2/25/2020 2:24 PM
# @Author : XiaoXia
# @Blog : https://xiaoxiablogs.top
# @File : lol_hero_photo.py
import datetime import requests
from lxml import etree
from pprint import pprint
import simplejson
import os # lol英雄网站
url_demo = "https://game.gtimg.cn/images/lol/act/img/js/hero/"
# lol英雄列表
hero_list = "https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js"
# 设置ua
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36"
headers = {
'User-Agent': ua
} def dirIsExist(dir_name: str):
"""
判断文件夹是否存在,不存在则创建
:param dir_name: 文件夹名称
"""
if not os.path.exists("./hero/"):
os.mkdir("./hero/")
path = "./hero/{}/".format(dir_name)
if not os.path.exists(path):
os.mkdir(path) def getJson(hero_url: str) -> requests.models.Response:
"""
获取json响应
:param hero_url: 英雄列表的获取链接
:return:
"""
response = requests.get(hero_url)
return response def getImagesUrl(hero_id: str) -> list:
"""
获取皮肤照片链接
:param hero_id: 英雄编号
:return: 皮肤照片数组
"""
response = getJson(url_demo + hero_id + ".js")
images = simplejson.loads(response.text)['skins']
image_list = []
'''
skinId: 图片的编号
name: 皮肤名称
mainImg: 图片地址
'''
for image in images:
image_dic = {
"name": image['name'],
"url": image['mainImg']
}
# 由于其中还有一些炫彩模型,所以要去除掉
if image_dic['url']:
image_list.append(image_dic) return image_list def saveImage(url: str, image_name: str, path: str):
"""
通过链接获取图片并且将图片保存到相应的目录下
:param path: 保存目录
:param image_name: 图片名称
:param url: 图片地址
"""
response = requests.get(url, headers=headers)
image_path = path + image_name + ".jpg" with response:
# 得到图片的二进制文件
image_file = response.content
with open(image_path, "wb+") as f:
f.write(image_file)
f.flush() if __name__ == "__main__":
# 该语句是用于计算程序运行时间的,不需要可以删除
start_time = datetime.datetime.now()
jsons = getJson(hero_list)
heros = simplejson.loads(jsons.text)["hero"]
for hero in heros:
'''
编号: heroId
称号: name
英文名: alias
中文名: title
'''
name = hero['name'] + '-' + hero['title'] name = name.replace("/", "")
# 获取每个英雄的皮肤名称及链接列表
image_lists = getImagesUrl(hero['heroId'])
# 创建该英雄的文件夹
dirIsExist(name)
for img in image_lists:
# 联盟中有K/DA的皮肤,所以需要将/去掉
print(img["name"].replace("/", ""))
saveImage(img['url'], img["name"].replace("/", ""), './hero/{}/'.format(name))
print("全部爬取完毕")
# 下面部分是用于计算程序运行时间的,不需要可以删除
end_time = datetime.datetime.now()
print("总用时为:", end_time - start_time)

Python3爬虫使用requests爬取lol英雄皮肤的更多相关文章

  1. python3爬虫-使用requests爬取起点小说

    import requests from lxml import etree from urllib import parse import os, time def get_page_html(ur ...

  2. python3爬虫-通过requests爬取图虫网

    import requests from fake_useragent import UserAgent from requests.exceptions import Timeout from ur ...

  3. python3爬虫-通过requests爬取西刺代理

    import requests from fake_useragent import UserAgent from lxml import etree from urllib.parse import ...

  4. Python爬取LOL英雄皮肤

    Python爬取LOL英雄皮肤 Python 爬虫  一 实现分析 在官网上找到英雄皮肤的真实链接,查看多个后发现前缀相同,后面对应为英雄的ID和皮肤的ID,皮肤的ID从00开始顺序递增,而英雄ID跟 ...

  5. python3 爬虫教学之爬取链家二手房(最下面源码) //以更新源码

    前言 作为一只小白,刚进入Python爬虫领域,今天尝试一下爬取链家的二手房,之前已经爬取了房天下的了,看看链家有什么不同,马上开始. 一.分析观察爬取网站结构 这里以广州链家二手房为例:http:/ ...

  6. 【Python3爬虫】我爬取了七万条弹幕,看看RNG和SKT打得怎么样

    一.写在前面 直播行业已经火热几年了,几个大平台也有了各自独特的“弹幕文化”,不过现在很多平台直播比赛时的弹幕都基本没法看的,主要是因为网络上的喷子还是挺多的,尤其是在观看比赛的时候,很多弹幕不是喷选 ...

  7. python3 [爬虫实战] selenium 爬取安居客

    我们爬取的网站:https://www.anjuke.com/sy-city.html 获取的内容:包括地区名,地区链接: 安居客详情 一开始直接用requests库进行网站的爬取,会访问不到数据的, ...

  8. 【Python3 爬虫】14_爬取淘宝上的手机图片

    现在我们想要使用爬虫爬取淘宝上的手机图片,那么该如何爬取呢?该做些什么准备工作呢? 首先,我们需要分析网页,先看看网页有哪些规律 打开淘宝网站http://www.taobao.com/ 我们可以看到 ...

  9. python 爬虫之requests爬取页面图片的url,并将图片下载到本地

    大家好我叫hardy 需求:爬取某个页面,并把该页面的图片下载到本地 思考: img标签一个有多少种类型的src值?四种:1.以http开头的网络链接.2.以“//”开头网络地址.3.以“/”开头绝对 ...

随机推荐

  1. word打印,和打印预览

    public void Print(object fileName)        {            try            {                foreach (Syst ...

  2. vue2.XX 提示[Vue warn]: Error in render: "TypeError: Cannot read property 'img' of undefined"

    item 是向后台请求的一条数据,里面包含img,但是却提示img未定义 父组件向子组件传递数据时, 子组件 具体代码: <img :src="item.img" /> ...

  3. Glob模块使用笔记

    一.Glob模块介绍 python中的glob模块用于查找文件目录和文件,并返回一个list.常用的方法有glob.glob()和glob.iglob().与os.listdir()都是查找文件,但有 ...

  4. 吴裕雄--天生自然python学习笔记:python爬虫PM2.5 实时监测显示器

    PM2.5 对人体的健康影响很大,所以空气中的 PM2.5 实时信息受到越来越多的关注. Python 的 Pandas 套件不但可以自动读取网页中的表格 数据 , 还可对数据进行修改.排序等处理,也 ...

  5. 数据结构与算法 python课后题(未完成)

    挖一个坑,先立个flag,后面慢慢填坑. 先放个其它人写的链接

  6. discussion|局限性|解释|猜测|前作与同行

    讨论是整篇论文的精华和灵魂,考查作者的文献积累量和对所研究内容的理解深度,作者需要阐述为什么结果是重要的,内容包括理论.应用.在其他其他领域的作用及应用,阐述时要求直接明确. 具体而言,首先概述最重要 ...

  7. 安装rpm包时遇到error: Failed dependencies:错误

    在linux下安装rpm包时经常会遇到下面这个问题: error: Failed dependencies: ............................................. ...

  8. 树剖裸题——BZOJ1036 树的统计

    #include<cstring> #include<cmath> #include<algorithm> #include<cstdio> #defi ...

  9. linux下安装glibc-2.14,解决“`GLIBC_2.14' not found”问题

    下载安装包:http://ftp.gnu.org/gnu/glibc/ 我下载的是glibc-2.14.1.tar.gz 解压:tar xzf glibc-2.14.1.tar.gz cd glibc ...

  10. GitHub之初始化

    1.github上新建repository. 2.本地 mkdir git-init-demo. 3.cd git-init-demo. 4.git clone https://github.com/ ...