壁纸 API 我们这里使用一个开源在 GitHub 上的必应壁纸 API 作为壁纸的来源
https://github.com/zenghongtu/bing-wallpaper
从 readme 当中我们可以知道,在 web 应用中我只需要使用如下引用即可
复制 < img src= "https://bingw.jasonzeng.dev/?w=800" />
实在是太方便了
接口使用 下面我们来看下该 API 的具体调用规则
1、传入 resolution 参数可以指定壁纸图像的分辨率。默认为1920x1080,可选值如下:
复制 UHD
1920 x1200
1920 x1080
1366 x768
1280 x768
1024 x768
800 x600
800 x480
768 x1280
720 x1280
640 x480
480 x800
400 x240
320 x240
240 x320
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 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 requests
def 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( )
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 上面代码就是获取前30张壁纸,我们可以修改range的参数,来获取不同数量的壁纸
抓取效果如下:
更换桌面 壁纸有了,下面我们就来进行自动切换桌面壁纸,这里使用win32con和win32gui操作桌面壁纸
复制 def windows_img( paper_path) :
k = win32api.RegOpenKeyEx ( win32con.HKEY_CURRENT_USER , "Control panel\\Desktop" , 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= 0
print( 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 += 1
if i== len( pic_list) : # 如果是最后一张图片,则重新到第一张
i= 0
if __name__ == '__main__' :
change_wallpaper( )
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 这样一个简单的自动切换桌面壁纸的工具就完成了,快来尝试一下吧!