Python3爬虫使用requests爬取lol英雄皮肤
此次爬取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英雄皮肤的更多相关文章
- python3爬虫-使用requests爬取起点小说
import requests from lxml import etree from urllib import parse import os, time def get_page_html(ur ...
- python3爬虫-通过requests爬取图虫网
import requests from fake_useragent import UserAgent from requests.exceptions import Timeout from ur ...
- python3爬虫-通过requests爬取西刺代理
import requests from fake_useragent import UserAgent from lxml import etree from urllib.parse import ...
- Python爬取LOL英雄皮肤
Python爬取LOL英雄皮肤 Python 爬虫 一 实现分析 在官网上找到英雄皮肤的真实链接,查看多个后发现前缀相同,后面对应为英雄的ID和皮肤的ID,皮肤的ID从00开始顺序递增,而英雄ID跟 ...
- python3 爬虫教学之爬取链家二手房(最下面源码) //以更新源码
前言 作为一只小白,刚进入Python爬虫领域,今天尝试一下爬取链家的二手房,之前已经爬取了房天下的了,看看链家有什么不同,马上开始. 一.分析观察爬取网站结构 这里以广州链家二手房为例:http:/ ...
- 【Python3爬虫】我爬取了七万条弹幕,看看RNG和SKT打得怎么样
一.写在前面 直播行业已经火热几年了,几个大平台也有了各自独特的“弹幕文化”,不过现在很多平台直播比赛时的弹幕都基本没法看的,主要是因为网络上的喷子还是挺多的,尤其是在观看比赛的时候,很多弹幕不是喷选 ...
- python3 [爬虫实战] selenium 爬取安居客
我们爬取的网站:https://www.anjuke.com/sy-city.html 获取的内容:包括地区名,地区链接: 安居客详情 一开始直接用requests库进行网站的爬取,会访问不到数据的, ...
- 【Python3 爬虫】14_爬取淘宝上的手机图片
现在我们想要使用爬虫爬取淘宝上的手机图片,那么该如何爬取呢?该做些什么准备工作呢? 首先,我们需要分析网页,先看看网页有哪些规律 打开淘宝网站http://www.taobao.com/ 我们可以看到 ...
- python 爬虫之requests爬取页面图片的url,并将图片下载到本地
大家好我叫hardy 需求:爬取某个页面,并把该页面的图片下载到本地 思考: img标签一个有多少种类型的src值?四种:1.以http开头的网络链接.2.以“//”开头网络地址.3.以“/”开头绝对 ...
随机推荐
- Windows下 webstorm安装tomcat配置svn并使用
先附上所需要的软件的下载地址:https://pan.baidu.com/s/1c2ripd2 1.下载并安装jdk以及配置jdk的环境变量 1)下载jdk,选择安装目录安装,我选择的是默认路径,安装 ...
- [flask]Restful接口测试简单的应用
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : shenqiang from flask import Flask,make_res ...
- 被这个C程序折腾死了
The C programming language 的第13页,1.5.3 行计数的那里,那个统计换行符个数的程序我好像无法运行,无论输入什么,按多少下enter,什么都出不来. #include& ...
- spring boot 配置文件properties和YAML详解
spring boot 配置文件properties和YAML详解 properties中配置信息并获取值. 1:在application.properties配置文件中添加: 根据提示创建直接创建. ...
- 经典题型-打印小星星(python)
# * # * * # * * * # * * * * # * * * * * x = 0 while x < 5: x += 1 # 每次循环需要给y赋值0.清空y中存储的值 y = 0 wh ...
- spring配置ConcurrentMap实现缓存
spring本身内置了对Cache的支持,本次记录的是基于Java API的ConcurrentMap的CacheManager配置. 1.xml文件中增加命名空间 <beans xmlns=& ...
- unittest(11)- get_data自定义取某几条测试数据
在get_data中定义取全部用例和取部分用例两种模式 # 1. http_request.py import requests class HttpRequest: def http_request ...
- 《JavaScript算法》二分查找的思路与代码实现
二分查找的思路 首先,从有序数组的中间的元素开始搜索,如果该元素正好是目标元素(即要查找的元素),则搜索过程结束,否则进行下一步. 如果目标元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半 ...
- JS计算日期加天数后的日期(起始日期+有效天数=截至日期)
/** * 优惠券有效期 * startDate:起始日期 * valueTime:有效天数 */ function transferCouponValueTime(startDate,valueTi ...
- Angular系列一:Angular程序架构
Angular程序架构 Angular程序架构 组件:一段带有业务逻辑和数据的Html服务:用来封装可重用的业务逻辑指令:允许你向Html元素添加自定义行为模块: 环境搭建 安装nodeJs安装好no ...