一键获取bing图片并设为自己的壁纸
原理如下:
出现的问题以及解决方案
- 通过上述思路写出的代码存在几个BUG:
1.wget和requests默认在程序开启时就请求,那么如果这时候没有网络的话,就会直接抛出异常
2.直接通过requests请求时由于过快,会导致偶尔请求不到的情况
- 解决问题的方案:
1.建立一个循环机制,只有当判断网络通畅的情况下才进行下载和请求
2.导入time模块,让其sleep几秒之后进行加载
最终实现的代码如下:
import wget
import json
import requests
import time
import win32api,win32con,win32gui
import os
def getjson():
url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
}
resp = requests.get(url=url,headers=headers)
htmldoc = json.loads(resp.content.decode("utf-8"))
finaurl = 'https://www.bing.com' + htmldoc['images'][0]['url']
return finaurl
def set_wallpaper(img_path):
reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "10")
win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img_path, win32con.SPIF_SENDWININICHANGE)
def downpic(url):
url = url
nowtime = time.time()
nowtime = int(nowtime)
nowtime = str(nowtime)
wget.download(url=url,out='./'+nowtime+'.jpg')
return nowtime+'.jpg'
def getfile():
file = os.getcwd()
filestr = file.split('\\')
finafile = filestr[0]
for i in range(1,len(filestr)):
finafile = finafile +"/"+ filestr[i]
filelis = []
filelis.append(file)
filelis.append(finafile)
return filelis
pass
def main():
webstatus = os.popen("ping -n 1 -l 8 baidu.com").read()
while(not("的回复: 字节=8" in webstatus)):
time.sleep(3)
webstatus = os.popen("ping -n 1 -l 8 baidu.com").read()
startchg()
def startchg():
picurl = getjson()
filename = downpic(picurl)
finafile = getfile()
finapic = finafile[0]+"\\"+filename
delfile = finafile[1]
print(delfile)
print(finapic)
set_wallpaper(finapic)
time.sleep(5)
os.remove(filename)
return 0
pass
if __name__=="__main__":
main()