壁紙 API
我們這里使用一個(gè)開源在 GitHub 上的必應(yīng)壁紙 API 作為壁紙的來源
?https://github.com/zenghongtu/bing-wallpaper

從 readme 當(dāng)中我們可以知道,在 web 應(yīng)用中我只需要使用如下引用即可
<img src="https://bingw.jasonzeng.dev/?w=800"/>
實(shí)在是太方便了
接口使用
下面我們來看下該 API 的具體調(diào)用規(guī)則
1、傳入 resolution 參數(shù)可以指定壁紙圖像的分辨率。默認(rèn)為1920x1080,可選值如下:
UHD
1920x1200
1920x1080
1366x768
1280x768
1024x768
800x600
800x480
768x1280
720x1280
640x480
480x800
400x240
320x240
240x320
UHD 就是高清,圖片比較大。
2、傳入 index 可以獲取某一天的圖片,0 表示今天,1 表示昨天,以此類推,index=random 表示隨機(jī)一天。
3、傳入 date 可以獲取從某一天到今天的圖片,比如 data=20210401。
4、傳入 w 和 h 可以指定圖片的寬度和高度。
5、傳入 qlt 可以指定圖片的質(zhì)量,取值范圍是 0 到 100。
舉個(gè)例子
我們直接在瀏覽器輸入如下地址
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"
}
可以說是相當(dāng)方便了
也可以直接在 css 當(dāng)中使用
background-image: url(https://bingw.jasonzeng.dev/?index=random);
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
Python 調(diào)用
下面我們看一下如何通過 Python 進(jìn)行調(diào)用,也很簡單
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()
上面代碼就是獲取前30張壁紙,我們可以修改range的參數(shù),來獲取不同數(shù)量的壁紙
抓取效果如下:

更換桌面
壁紙有了,下面我們就來進(jìn)行自動(dòng)切換桌面壁紙,這里使用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) # 刷新桌面
然后就是從已經(jīng)下載的壁紙當(dāng)中選擇圖片
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) # 設(shè)置壁紙更換間隔
i += 1
if i==len(pic_list): # 如果是最后一張圖片,則重新到第一張
i=0
if __name__ == '__main__':
change_wallpaper()
這樣一個(gè)簡單的自動(dòng)切換桌面壁紙的工具就完成了,快來嘗試一下吧!