最近发现 http://cn.bing.com/ 的每日背景图片质量还不错,将其下载作为系统桌面应该是一个好的想法,顺便练练python。
花了半天时间做了出来,实现效果:开机自动启动,将bing网址的背景图下载,重命名为系统当前时间,并自动更新为系统桌面。
蛋疼的是,下载好的jpg文件需要另存为bmp文件,因为设置桌面背景的api貌似只支持bmp格式。
目前只做到了爬取jpg图片,不知道是不是还有其他的图片格式,后面再验证。
正则表达式不太懂,瞎写的,特别是括弧、斜杠比较烦,后面如果出问题再改动。
————————————————————————分割线,以下是正文—————————————————————————————
使用的版本为:python 3.5,开发工具PyCharm。
需要用到图像处理的库,将jpg文件转为bmp文件:PIL,但好像已经不维护了,不支持python3,链接:http://www.pythonware.com/products/pil/
用了一个替代库,链接https://pypi.python.org/pypi/Pillow/3.2.0
还需要用到windows的一些库,下载链接:https://sourceforge.net/projects/pywin32/
开机自动运行的方式:创建cmd文件,写入python pyPath(pyPath为.py文件的路径),将cmd文件放入开始->所有程序->启动。
参考了别处的代码,稍微做了一点点改动,参考代码链接:http://www.jb51.net/article/65421.htm,最终代码如下。
# -*- coding: utf-8 -*-
import urllib.request
import time
import os
import re
from PIL import Image
import win32api
import win32gui
import win32con
class StealBing:
def __init__(self):
self.content = urllib.request.urlopen('http://cn.bing.com/').read()
self.bgImageUrl = ''
self.localFileName = ''
self.localBMPFileName = ''
def parserImageURL(self):
reg = re.compile('g_img={url.*(http:.*?jpg)')
data = self.content.decode('utf-8')
self.bgImageUrl = reg.findall(data)
def createLocalFileName(self):
path = 'K:/Bing/'
if not os.path.exists(path):
os.mkdir(path)
randomStr = time.strftime("%Y%m%d", time.localtime())
self.localFileName = path + randomStr + '.jpg'
self.localBMPFileName = path + randomStr + '.bmp'
def downloadImage(self):
if self.bgImageUrl == '':
self.parserImageURL()
if self.localFileName == '':
self.createLocalFileName()
path = self.bgImageUrl[0].replace('\\', '')
urllib.request.urlretrieve(path, self.localFileName)
def updateBGImage(self):
img = Image.open(self.localFileName)
img.save(self.localBMPFileName)
os.remove(self.localFileName)
#k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
#win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") # 2拉伸适应桌面,0桌面居中
#win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, self.localBMPFileName, 1+2)
if __name__ == '__main__':
stealBing = StealBing()
stealBing.downloadImage()
stealBing.updateBGImage()
———————————————————————将py文件打包为exe——————————————————————————————
cmd:pip install pyintaller 安装 pyintaller
pyi-makespec.exe py文件路径
pyinstaller spec文件路径
OK...
或者直接:pyinstaller -F -w py文件路径