Skip to content

Instantly share code, notes, and snippets.

@HakurouKen
Last active January 4, 2016 14:47
Show Gist options
  • Save HakurouKen/5cdcd9ace6cd5cd6f27c to your computer and use it in GitHub Desktop.
Save HakurouKen/5cdcd9ace6cd5cd6f27c to your computer and use it in GitHub Desktop.
get bing daily wallpaper.
#! /usr/bin/python
# -*- coding: utf-8 -*-
import urllib,urllib2
import time
import json
import os
import re
import sys
def get_req_url():
url = "http://cn.bing.com/HPImageArchive.aspx?{}"
params = {
"format": "js",
"idx": 0,
"n": 1,
"nc": int(time.time()*1000),
"pid": "hp"
}
return url.format(urllib.urlencode(params))
def get_info():
url = get_req_url()
try:
resp = urllib2.urlopen(url).read()
result = json.loads(resp)
return result["images"][0]
except:
return None
def download(filename,url):
with open(filename.encode('utf-8'),'wb') as f:
content = urllib2.urlopen(url).read()
f.write(content)
if __name__ == '__main__':
PATHNAME = 'wallpaper'
if not os.path.isdir(PATHNAME):
os.mkdir(PATHNAME)
info = get_info()
url = info['url'] if info['url'].startswith('http') else 'http://s.cn.bing.net{}'.format(info['url'])
suffix_match = re.search(r'\.\w*?$',url)
if suffix_match:
suffix = suffix_match.group()
else:
suffix = '.jpg'
filename = re.sub(re.compile(r'\s\(.*\)'),'',info['copyright'])
download(os.path.join(PATHNAME, info['enddate'] + '-' + filename + suffix), url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment