# -*- coding:utf-8 -*-
import json
import urllib.request
import requests
import ctypes
import os.path
#接口调用(get形式)
def request_get(url, param):
fails = 0
while True:
try:
if fails >= 20:
break
ret = requests.get(url=url, params=param, timeout=10)
if ret.status_code == 200:
text = json.loads(ret.text)
else:
continue
except:
fails += 1
print('网络连接出现问题, 正在尝试再次请求: ', fails)
else:
break
return text
#接口调用(post调用)
def request_post(url, param):
fails = 0
while True:
try:
if fails >= 20:
break
headers = {'content-type': 'application/json'}
ret = requests.post(url, json=param, headers=headers, timeout=10)
if ret.status_code == 200:
text = json.loads(ret.text)
else:
continue
except:
fails += 1
print('网络连接出现问题, 正在尝试再次请求: ', fails)
else:
break
return text
#将图片保存本地
def save_img(img_url, dirname):
# 保存图片到磁盘文件夹dirname中
try:
if not os.path.exists(dirname):
print('文件夹', dirname, '不存在,重新建立')
# os.mkdir(dirname)
os.makedirs(dirname)
# 获得图片文件名,包括后缀
basename = "bing.jpg"
# 拼接目录与文件名,得到图片路径
filepath = os.path.join(dirname, basename)
# 下载图片,并保存到文件夹中
urllib.request.urlretrieve(img_url, filepath)
except IOError as e:
print('文件操作失败', e)
except Exception as e:
print('错误 :', e)
print("Save", filepath, "successfully!")
return filepath
#必应接口调用
a=request_get('https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN',"")
#将每日必应接口的图片保存到本地
filepath = save_img('https://cn.bing.com'+(a["images"])[0]["url"], "D:\\bingImg")
#桌面背景切换成本地保存的壁纸
ctypes.windll.user32.SystemParametersInfoW(20, 0,filepath, 3)
建立bat文件 并编辑内容
将bat文件放入C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp下