国家地理每日一图自动更新Code
本代码能够实现《国家地理:每日一图》的自动下载,自动设置,文件体积仅为2KB。
1 # -*- coding: utf-8 -*-
2 import ctypes
3 from datetime import datetime
4 import urllib
5 from PIL import Image
6 import socket
7
8 import os
9 import sys
10 import re
11
12 #dir like NationalGeographic/year/month/
13 today = datetime.today()
14 root = 'E:/NationalGeographic/'
15 STOREDIR = root + str(today.year) + '/' + str(today.month) + '/'
16
17 def setWallpaperFromBMP(imagepath):
18 SPI_SETDESKWALLPAPER = 20
19 ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, imagepath , 3)
20
21 def setWallPaper(imagePath):
22 """Given a path to an image, convert it to bmp and set it as wallpaper"""
23 bmpImage = Image.open(imagePath)
24 newPath = root + 'todayWallPaper.bmp'
25 bmpImage.save(newPath, "BMP")
26 setWallpaperFromBMP(newPath)
27
28 def getPicture(fname):
29 sock = urllib.urlopen("http://photography.nationalgeographic.com/photography/photo-of-the-day/")
30 htmlSource = sock.read()
31 sock.close()
32
33 p = re.compile('http://images.nationalgeographic.com/.*(?:1600x1200|990x742).*\.jpg')
34 match = p.findall(htmlSource)
35 print match
36 urllib.urlretrieve(match[0], fname)
37
38 def setWallpaperOfToday():
39 filename = STOREDIR + str(today.strftime('%Y%m%d')) + '.jpg'
40 print filename
41 getPicture(filename)
42 setWallPaper(filename)
43
44 setWallpaperOfToday()
运行环境:Windows XP + Python 2.7
将上述代码保存在任意位置后,在windows任务计划中添加就可以了,设置自动运行时间在每天下午3:00即可。(考虑到米国时差,一般更新时间在下午2点左右)