import urllib.request
import requests
import os.path
import ctypes
import sys
def get_image_url(raw_img_url="https://area.sinaapp.com/bingImg/"):
r = requests.get(raw_img_url)
img_url = r.url
print("img_url:", img_url)
return img_url
def save_img(img_url, dirname):
try:
if not os.path.exists(dirname):
os.makedirs(dirname)
basename = "bing.jpg"
filepath = os.path.join(dirname, basename)
urllib.request.urlretrieve(img_url, filepath)
except IOError as e:
print("IO Failed", e)
except Exception as e:
print("ERROR:", e)
print("save", filepath, "successfully" + "!" * 10)
return filepath
def set_img_as_wallpaper(filepath):
ctypes.windll.user32.SystemParametersInfoW(20, 0, filepath, 0)
print("*" * 32)
print("set wallpaper successfully")
def del_img(filepath):
try:
if not os.path.exists(filepath + "\\" + "bing.jpg"):
print("No img can be del" + "*" * 32)
else:
os.remove(filepath + "\\" + "bing.jpg")
print("DEL" + "*" * 10 + "successfully")
except Exception as e:
print("No img del", e)
if __name__ == '__main__':
dirname = "D:\\BINGIMAGE"
del_img(dirname)
img_url = get_image_url()
filepath = save_img(img_url, dirname)
set_img_as_wallpaper(filepath)