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.以“/”开头绝对 ...
随机推荐
- Java接口和抽象类区别
1.抽象类 [public] abstract class ClassName { abstract void fun(); } extends 包含抽象方法的类称为抽象类,但并不意味着抽象类中只能有 ...
- Struts2加载自定义库注意事项
新建Struts2项目,添加Struts2的jar包时,往往通过导入自定义库的方式,导入自定义库时,有个地方必须要设置,否则项目无法正常执行,如图所示: 必须要按照上述方式对自定义库进行加载!
- python3多线程应用详解(第三卷:图解多线程中join,守护线程应用)
- HDU 5978 To begin or not to begin
题目:HDU 5978 To begin or not to begin 思路: 题目意思是说:给出n个黑球,一个红球,拿到红球的人胜利.如果先手有优势的输出 1 ,没有优势的输出 2 ,机会均等则输 ...
- CF-1117C-Magic Ship
二分 C - Magic Ship GNU C++11 Accepted 31 ms 1700 KB #include "bits/stdc++.h" using namespac ...
- 写个匹配某段html dom代码某属性的正则匹配方法
private static string GetHtmlDomAttr(string html, string id, string attrname) { string xmatchstring ...
- FOR xml path 这么爽的SQL命令,居然今天才知道
select stuff((select ControlName from Base_Controls FOR xml path('')),1,1,'')
- supervised learning|unsupervised learning
监督学习即是supervised learning,原始数据中有每个数据有自己的数据结构同时有标签,用于classify,机器learn的是判定规则,通过已成熟的数据training model达到判 ...
- mysql手动开启
1.cd C:\Program Files\mysql-5.7.20-winx64\bin2.mysqld --install mysql5.73.net start mysql5.7
- 使用apktool反编译apk文件
Apktool https://ibotpeaches.github.io/Apktool/install/ 下载地址:Apktool https://bitbucket.org/iBotPeache ...