用Python下载壁纸并自动更换桌面
壁纸 API
我们这里使用一个开源在 GitHub 上的必应壁纸 API 作为壁纸的来源
https://github.com/zenghongtu/bing-wallpaper
从 readme 当中我们可以知道,在 web 应用中我只需要使用如下引用即可
@@##@@
实在是太方便了
接口使用
下面我们来看下该 API 的具体调用规则
1、传入 resolution 参数可以指定壁纸图像的分辨率。默认为1920x1080,可选值如下:
UHD1920x12001920x10801366x7681280x7681024x768800x600800x480768x1280720x1280640x480480x800400x240320x240240x320
UHD 就是高清,图片比较大。
2、传入 index 可以获取某一天的图片,0 表示今天,1 表示昨天,以此类推,index=random 表示随机一天。
3、传入 date 可以获取从某一天到今天的图片,比如 data=20210401。
4、传入 w 和 h 可以指定图片的宽度和高度。
5、传入 qlt 可以指定图片的质量,取值范围是 0 到 100。
举个例子
我们直接在浏览器输入如下地址
http://bingw.jasonzeng.dev?resolutinotallow=UHD&index=random&w=1000&format=json
Output:
{ "startdate": "20220105", "copyright": "Plate-billed mountain toucan in Bellavista Cloud Forest Reserve, Ecuador (© Tui De Roy/Minden Pictures)", "urlbase": "/th?id=OHR.MountainToucan_EN-US7120632569", "title": "A plate-billed mountain toucan", "url": "https://www.bing.com/th?id=OHR.MountainToucan_EN-US7120632569_UHD.jpg&w=1000"}
可以说是相当方便了
也可以直接在 css 当中使用
background-image: url(https://bingw.jasonzeng.dev/?index=random);height: 100%;background-position: center;background-repeat: no-repeat;background-size: cover;
Python 调用
下面我们看一下如何通过 Python 进行调用,也很简单
import requestsdef get_wallpaper():for i in range(30):url = "https://bingw.jasonzeng.dev?resolutinotallow=UHD&index=%s" % str(i)print(url)res = requests.get(url)with open("wallpaper/" + "%s.jpg" % str(i),"wb") as w:w.write(res.content)if __name__ == "__main__":get_wallpaper()
上面代码就是获取前30张壁纸,我们可以修改range的参数,来获取不同数量的壁纸
抓取效果如下:
更换桌面
壁纸有了,下面我们就来进行自动切换桌面壁纸,这里使用win32con和win32gui操作桌面壁纸
def windows_img(paper_path):k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control panelDesktop", 0, win32con.KEY_SET_VALUE) # 在注册表中写入属性值win32api.RegSetValueEx(k, "wapaperStyle", 0, win32con.REG_SZ,"2")# 0 代表桌面居中 2 代表拉伸桌面win32api.RegSetValueEx(k, "Tilewallpaper", 0, win32con.REG_SZ,"0")win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, paper_path, win32con.SPIF_SENDWININICHANGE) # 刷新桌面
然后就是从已经下载的壁纸当中选择图片
def change_wallpaper():pic_list = os.listdir("wallpaper")# 得到文件路径下的图片,列表类型i=0print(pic_list)while True:pic = "wallpaper"+'{}'.format(pic_list[i])abspath_pic = os.path.abspath(pic)windows_img(abspath_pic)print(abspath_pic)time.sleep(1000)# 设置壁纸更换间隔i += 1if i==len(pic_list):# 如果是最后一张图片,则重新到第一张i=0if __name__ == '__main__':change_wallpaper()
这样一个简单的自动切换桌面壁纸的工具就完成了,快来尝试一下吧!