Python 获取LOL皮肤(二) 加了进程挂起随机时间

import requests
import time
import random

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36"
}

def getrandom():
    return  random.uniform(1,5)#生成一个指定范围内的浮点数

def get_id():
    url = "https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js"
    res = requests.get(url,headers=headers).json()
    lol_list = res["hero"]
    list1 = []
    for lol in lol_list:
        list1.append(lol["heroId"])
    return list1

def get_skins(lol_lists):
    for i in lol_lists:
        sec = getrandom()
        time.sleep(sec)
        print("--have sleep -- = -- %lf" %sec)
        url = "https://game.gtimg.cn/images/lol/act/img/js/hero/{}.js".format(i)
        response = requests.get(url, headers = headers).json()
        skins_list = response["skins"]
        for j in skins_list:
            item = {}
            item["name"] = j["name"]
            item["mainImg"] = j["mainImg"]
            print(item)

            if item["mainImg"]:
                conn = requests.get(item["mainImg"],headers=headers).content
                try:
                    with open("images/" + item["name"] + ".jpg","wb") as f:
                        f.write(conn)
                except FileNotFoundError:
                    print("[Errno 2] No such file or directory %s" %item["name"])
                except BaseException:
                    print("BaseException")
                else:
                    print("正在下载%s" %item["name"])
            else:
                print("没有数据")

lol_lists = get_id()
get_skins(lol_lists)
print("下载完成!!!")

加入try except , 是为了避免因为FIleNotFoundError 的异常而中断

进程挂起  Python time sleep()

import time

随机数 Python random() 

import random
print(random.random()) #用于生成一个0到1之间的随机浮点数
print(random.uniform(1,3))# 用于生成一个指定范围内的随机浮点数
print(random.uniform(3,1))# 两个参数一个是上限,一个是下限。
print(random.randint(1,3)) # 用于生成一个指定范围内的整数。
#random.randrange([start],stop[,step]) 从指定范围内,按指定的基数递增的集合中获取一个随机数
print(random.randrange(0,100,2)) # 取 0到100之间的随机偶数
 
# random.choice 从序列中获取一个随机元素。其函数原型为random.choice(sequence),参数sequence表示
# 一个有序类型。
print(random.choice('改变世界')) # 世
print(random.choice(['sunshine','is','lower'])) #lower
print(random.choice(('sunshine','always','18')))  # 18
 
# random.shuffle(x[,random]) 用于将一个列表中的元素打乱。
 
s = ['改','变','世','界']
random.shuffle(s)
print(s) # ['变', '世', '改', '界']
 
# random.sample(sequence,k) 从指令序列中随机获取指定长度的片段。sample函数不会修改原有的序列。
l = [1,2,3,4,5,6,7,8]
print(random.sample(l,3)) # [7, 3, 5]

引用来自于:https://www.cnblogs.com/Uncle-Guang/p/9008903.html
发布了118 篇原创文章 · 获赞 85 · 访问量 48万+

猜你喜欢

转载自blog.csdn.net/c_lanxiaofang/article/details/103958258