python3 下载必应每日壁纸(一)

这是👉python3 下载必应每日壁纸(一)👈的摘要

环境:

win10,python3

前言:

想换壁纸了,so,搜搜github,发现有有人用python写的获取必应每日壁纸,看了看,也不难,就自己也写了一个

首先:找到了一个必应的API

json_url = "http://cn.bing.com/HPImageArchive.aspx?format=js&n=1&idx=0"

改api返回json数据,

参数n代表返回几条

参数idx代表返回那一天的,0是今天的,-1是明天的,1是昨天的

流程:

获取json数据解析出时间,文件名,图片url

然后下载

code

import json
from urllib import request
import os


class BingWallpaper():
    """下载必应壁纸"""
    def __init__(self):
        self.filePath = "G:\Pictures\DesktoBackGround"
        self.hosts = "http://cn.bing.com"
        self.imgDate = ""
        self.imgUrl = ""
        self.imgFileName = ""

    def __get_json_data(self, idx = 0):
        # idx = 0是今天的,-1明天,1昨天
        json_url = self.hosts+"/HPImageArchive.aspx?format=js&n=1&idx={}".format(idx)
        try:
            data = request.urlopen(json_url).read().decode("utf-8")
            json_data = json.loads(data)
            self.imgDate = json_data["images"][0]["enddate"]
            self.imgUrl = self.hosts + json_data["images"][0]["url"]
            self.imgFileName = self.imgDate+"_"+json_data["images"][0]["url"].split("/")[4]
        except Exception as f:
            print("get_json_data:",f)

    def __down_img(self):
        with request.urlopen(self.imgUrl) as f:
            data = f.read()  
       # 图片存的路径为 G:\Pictures\DesktoBackGround目录
            with open(str(self.filePath+os.sep+self.imgFileName), mode="wb") as f:
                f.write(data)

    def save_img(self, idx = 0):
        self.__get_json_data(idx)
        self.__down_img()
        print("{}download!".format(self.imgFileName))

if __name__ == '__main__':
    print("path:",__file__)
    print("run...")
    wall = BingWallpaper()
    wall.save_img()
    print("end!")
    exit = input("please enter any key to exit...")
updatedupdated2019-11-202019-11-20