一 谎仲、前言
最近在windows商店看到一個(gè)很好玩的應(yīng)用呛哟,他能每天自動(dòng)爬取bing搜索的圖片設(shè)置為你的桌面壁紙,每天都能自動(dòng)下載bing圖片設(shè)置為桌面壁紙硼控,可惜只有付費(fèi)才能自動(dòng)更換壁紙港柜。下面讓我們一起來用python實(shí)現(xiàn)這一功能吧~
二请契、思路
整個(gè)程序過程非常簡(jiǎn)單,首先獲取圖片鏈接夏醉,然后使用 urllib.request 庫把圖片保存到電腦里姚糊,再使用Cpython接口調(diào)用Windows API改變壁紙。
三授舟、代碼實(shí)現(xiàn)
import ctypes
import urllib.request
import json
import getpass
import time
def get_bing_photo():
url = 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'
res = urllib.request.urlopen(url)
json_txt = res.read()
txt = json.loads(json_txt)
url = 'https://www.bing.com/' + txt['images'][0]['url']
return url
def set_photo(url,num):
photo = urllib.request.urlopen(url)
d = photo.read()
dizhi = "C:\\Users\\"+str(getpass.getuser())+"\\Pictures\\"+str(num)+".jpg"
print(dizhi)
f = open(dizhi, "wb")
f.write(d)
f.close()
filepath = dizhi
ctypes.windll.user32.SystemParametersInfoW(20, 0, filepath, 0)
if __name__ == "__main__":
while True:
#使用unsplash的隨機(jī)高清圖
url = 'https://source.unsplash.com/random/4096x2160'
#使用bing接口
#url = get_bing_photo()
#下載的圖片保存地址
f = open("C:\\Users\\"+str(getpass.getuser())+"\\Pictures\\tmp",'a+')
f.seek(0)
num = f.read()
if num == '':
num = '0'
f.seek(0)
f.truncate()
num = int(num) + 1
f.write(str(num))
f.close()
set_photo(url,num)
#設(shè)置更改壁紙的時(shí)間,每隔100秒換一張
time.sleep(100)
四救恨、總結(jié)
這個(gè)小項(xiàng)目非常簡(jiǎn)單,但是卻非常實(shí)用释树。Unsplash 的高清圖真的超級(jí)超級(jí)好看肠槽,快自己動(dòng)手試一下吧。
ps:如果你不想自己動(dòng)手敲代碼奢啥,可以下載我已經(jīng)打包好的exe文件秸仙。關(guān)注我的個(gè)人公眾號(hào)(木羽的樹:muyudeshu),回復(fù) "自動(dòng)換壁紙" 可以獲取下載鏈接哦~