基于Python爬取Bing每日壁纸

根据bing提供的Api获取每日壁纸的下载信息

下载每日壁纸到对应的月份目录下

源代码

import requests
import re
from urllib import request
import os
import random
import shutil
import datetime
from dateutil.relativedelta import relativedelta
from lxml import html
import json

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
res_html = requests.get("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&uhd=1", headers=headers)
res = res_html.content.decode("utf-8")
json_res = json.loads(res)
url = json_res["images"][0]["url"]
# url截取
url = url[:url.find('&')];
pictureTitle = json_res["images"][0]["copyright"]
endDate = json_res["images"][0]["enddate"]
# 截取标题
pictureTitle = pictureTitle[:pictureTitle.rfind('(')].strip()
# 拼接url
url = "https://www.bing.com{}".format(url)
# 获取当前日期信息
now = datetime.datetime.now()
currYear = now.year
currDate = datetime.datetime.strftime(now, "%Y-%m")
# 保存的路径(自动创建年月目录)
path = "E:/bingPic/download"
monthDirPath = path + "/{}/{}".format(currYear,currDate)
# 月份路径(不存在则创建)
if not os.path.exists(monthDirPath):
    os.makedirs(monthDirPath)

# 图片下载路径
picDownLoadPath = monthDirPath + "/{}-{}.jpg".format(pictureTitle, endDate)
# 图片不存在->下载
if not os.path.exists(picDownLoadPath):
    request.urlretrieve(url, picDownLoadPath)
    print(pictureTitle, "下载成功")