下面的代码在我写此博客时编辑通过,很简单,如果Bing的背景图片格式发生变化,请修改对应的正则匹配代码即可。
#-------------------------------------------------------------------------------
# Name: BingWallPaper
# Purpose:
#
# Author: xxh
#
# Created: 28-03-2022
# Copyright: (c) xxh 2022
# Licence: <your licence>
#-------------------------------------------------------------------------------
import requests
import re
import win32gui
import os
import time
from PIL import Image
# 注册表定位到“HKEY_CURRENT_USER\Control Panel\Desktop中WallPaper一项,键值即为壁纸地址
# 设置壁纸
def setWallpaper(imgPath):
win32gui.SystemParametersInfo(20, imgPath, 3)
# 下载图片
def downImg(IMAGE_URL):
# 图片以当天日期命名,这里默认为当前路径,实际使用时可以指定一个壁纸存放的专门路径
fileName = time.strftime("%Y-%m-%d", time.localtime()) +'.jpg'
r = requests.get(IMAGE_URL)
with open(fileName, 'wb') as f:
f.write(r.content)
return fileName
def main():
res = requests.get('https://cn.bing.com/')
res.encoding = 'utf-8'
# res.text为网页源码,这里要用到的是图片
# <link rel="preload" href="https://s.cn.bing.net/th?id=OHR.Kawachi_ZH-CN6964965791_1920x1080.jpg&rf=LaDigue_1920x1080.jpg" as="image" id="preloadBg" />
pattern = re.compile(r'href="(https://s\.cn\.bing\.net/th\?id=.*\.jpg)" as=')
result = pattern.findall(res.text)
# result[0]:https://s.cn.bing.net/th?id=OHR.Kawachi_ZH-CN6964965791_1920x1080.jpg&rf=LaDigue_1920x1080.jpg
fileName = downImg(result[0])
newFileName = fileName[:-3]+'bmp'
# 转换文件格式为bmp
im = Image.open(fileName)
im.convert('RGB').save(newFileName,'BMP')
# 设置壁纸
setWallpaper(os.getcwd()+'/'+newFileName)
if __name__ == '__main__':
main()