Python 每日bing图片下载

每日bing图片下载工具,程序运行时会在运行目录下新建images文件夹,图片文件保存在images文件夹下。默认下载8天的每日bing图片

在github上查看

主要函数说明:
get_bing_img() # 下载今天和前七天的8张每日bing图片
get_img() # 下载今天的每日bing图片
# 2020/04/02 by joywua
import json
import os
from urllib import request


def get_json():
    api_url = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=10"
    res = request.urlopen(api_url).read().decode()
    data = json.loads(res)
    return data


def get_bing_img():
    """
    一次性下载八天的bing每日图片,包括当天bing图片和前七天的每日bing图片
    文件下载位置位于当前文件路径下的images文件夹
    """
    try:
        data = get_json()
        for i in range(len(data["images"])):
            startdate = data["images"][i]["startdate"]
            img_hsh = data["images"][i]['hsh']
            img_url = "http://www.bing.com"+data["images"][i]["url"]
            filename = ("images/%s-%s.%s" %(startdate, img_hsh, "jpg"))
            request.urlretrieve(img_url, filename)
            print(filename)
    except Exception as e:
        print(e)


def get_img():
    """
    下载今天的每日bing图片
    """
    try:
        data = get_json()
        startdate = data["images"][0]["startdate"]
        img_hsh = data["images"][0]['hsh']
        img_url = "http://www.bing.com"+data["images"][0]["url"]
        filename = ("images/%s-%s.%s" %(startdate, img_hsh, "jpg"))
        request.urlretrieve(img_url, filename)
        print(filename)
    except Exception as e:
        print(e)


if __name__ == "__main__":
    try:
        os.mkdir("images")
    except Exception as e:
        print(e)
    print(os.path.abspath("images"))
    get_bing_img()
上一篇
下一篇