Bing背景作为桌面壁纸

时间:2017-03-10 12:35:14

标签: python

我编写了以下代码,使用Python 2.7将bing背景设置为Windows 10中的桌面墙纸。问题是有时图像没有正确下载,在这种情况下正在设置默认壁纸。当发生这种情况时,图像文件被保存在所需的目录中,但当我尝试打开它时,我在图片查看器中收到一条消息,“我们无法打开此文件“。我不明白为什么会这样。

import re
import os
import time
import json
import requests
import urllib
import ctypes
import socket

def wallpaper():
 URL = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
 image_data = json.loads(requests.get(URL).text)
 image_url = 'http://www.bing.com' + image_data['images'][0]['url']
 image_download_url = 'http://www.bing.com/hpwp/' + image_data['images'][0]['hsh']
 image_name = image_url[re.search("rb/", image_url).end():re.search('_EN', image_url).start()] + '.jpg'
 filepath = "C:\Users\Admin\Pictures\Bing_Wallpapers" + "\\" + image_name
 urllib.urlretrieve(image_download_url, filename=filepath)
 SPI_SETDESKWALLPAPER = 20
 ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, filepath, 0)

def internet(host="8.8.8.8", port=53, timeout=3):
 try:
  socket.setdefaulttimeout(timeout)
  socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
  return True
 except Exception as ex:
  print ex.message
  return False
try:
 wallpaper()
except:
 while(1):
     if(internet()):
         break
 wallpaper()

0 个答案:

没有答案