首先运行
pip install pypiwin32
保存下面代码为 .py 文件,运行即可。
- import requests
- import time
- import os
- import random
- g_headers = {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
- '(KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
- }
- def get_bing_image_urls(num):
- """
- 从cn.bing.com下载每日的桌面壁纸
- :param num: 最多获取壁纸数
- :return: 返回获取的壁纸地址列表
- """
-
- start_url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx={}&n=1'
- imgs = []
- page = 1
- while len(imgs) < num and page < num*2:
- page += 1
- page_url = start_url.format(page)
- try:
- r = requests.get(page_url, headers=g_headers).json()
- img = 'https://cn.bing.com' + r['images'][0]['url']
- if imgs.count(img) <= 0:
- imgs.append(img)
- else:
- break
- except:
- pass
- return imgs
- def download_image(url, savepath):
- """
- 根据图片地址下载图片至指定路径
- :param url: 图片url地址
- :param savepath: 图片保存路径
- :return: 下载是否成功
- """
- try:
- r = requests.get(url, headers=g_headers, stream=True)
- if r.status_code != 200:
- return False
- open(savepath, 'wb').write(r.content)
- return True
- except:
- return False
- def get_image_id(url):
- """
- 从URL地址获取图片的参数id信息
- :param url: bing图片url地址
- :return: 图片id
- """
- try:
- paras = url[url.find('?')+1:].split('&')
- for p in paras:
- kv = p.split('=')
- if kv[0] == 'id':
- return kv[1].strip()
- except:
- pass
- return url
- def set_desktop_image(img):
- """
- 将图片设置为桌面壁纸
- :param img: 图片
- :return:
- """
- import win32gui
- import win32con
- import win32api
- key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
- "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
- win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
-
- win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
- win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, os.path.abspath(img), 1 + 2)
- def auto_change_desktop_image(img_dir, order='rand'):
- """
- 根据指定的壁纸目录,定时更新桌面壁纸,当前日期变化后会退出
- :param img_dir: 壁纸目录
- :param order: 图片更新顺序,默认为顺序,rand为随机
- :return:
- """
- files = os.listdir(img_dir)
- images = []
- for file in files:
- temp = os.path.join(img_dir, file)
- if os.path.isfile(temp):
- images.append(temp)
- index = 1
- if order == 'rand':
- index = random.randint(0, len(images) - 1)
- index = index % len(images)
- set_desktop_image(images[index])
- print(time.time(), ' 已设置桌面壁纸为:', images[index])
- if __name__ == '__main__':
-
- urls = get_bing_image_urls(20)
- save_dir = './' + time.strftime('%Y%m%d', time.localtime(time.time()))
- if not os.path.exists(save_dir):
- os.makedirs(save_dir)
- for url in urls:
- name = get_image_id(url)
- save_path = save_dir + '/' + name
- print('下载', url, '成功' if download_image(url, save_path) else '失败')
-
- auto_change_desktop_image(save_dir, 'rand')