Python_必应每日壁纸更换(Python2.7)

Python_必应每日壁纸更换(Python2.7)

因为必应搜索每天会更换一张壁纸,于是决定每天下载一张壁纸来进行更换

现已完美更换壁纸

环境:

  • 上次使用的python3

  • 这次使用 python2.7 + Image + urllib2 + pywin32

难点:

  • 有时候会出现编码错误,得在py文件首行加上下面那句话
# This Python file uses the following encoding: utf-8
...
  • urllib的使用

python2.7和python3的urllib的使用和导入方式不同

#python3
import urllib.request
# 连接网络
def connect_Net(strUrl) :
    request = urllib.request.Request(strUrl)
    response = urllib.request.urlopen(request)
    data = response.read()
    return data

#python2.7
import urllib2
# 从网络获取数据
def connect_Net(strUrl) :
    response = urllib2.urlopen(strUrl)
    data = response.read()
    return data
  • Image的安装(√)

python3和python2.7导入此模块的方法不一样

#Image安装
pip install pillow
#python3
import Image
#python2.7
from PIL import Image
  • win32gui的安装(√)

因为win32gui在pywin中,当时不知道,所以找了很久

可以在pywin32找到对应版本下载,然后直接安装即可

注意pip install win32gui 的安装方式是无效的

接下来的内容和以前用python3写的流程差不多,详情可看Python_必应每日壁纸更换

  • 注意
    • 正则表达式的url地址是

url: "/az/hprichbg/rb/HallstattAustria_ZH-CN10534000934_1920x1080.jpg"
url:与“….jpg” 之间有一个空格,所以在写正则的时候需要注意
patternImg = r'url: "(.*jpg)"'

完整代码:

# This Python file uses the following encoding: utf-8
import urllib2
import re
from PIL import Image
import win32gui
import win32con
import win32api

# 从网络获取数据
def connect_Net(strUrl) :
    response = urllib2.urlopen(strUrl)
    data = response.read()
    return data

# :url(/az/hprichbg/rb/LaGrandeNomade_ZH-CN10098798714_1920x1080.jpg)
# 获取URL
def get_DailyPicUrl(data) :
    patternImg = r'url: "(.*jpg)"'
    picUrl = re.findall(patternImg, data);
    return picUrl[0];


#http://cn.bing.com/az/hprichbg/rb/GreatSaltLake_ZH-CN12553220159_1920x1080.jpg
def download_DailyPic(picUrl) :
    # 地址
    picUrl = 'http://cn.bing.com' + picUrl
    picData = connect_Net(picUrl)
    # 图片列表
    picList = str(picUrl).split('/')
    picName = picList[len(picList) - 1]
    # 保存到本地
    with open(picName, 'wb') as f:
        f.write(picData)

    return picName

StoreFolder = "D:\\Learn\\Python\\wallpaper"

# 该代码摘自网络    
def setWallPaper(imagePath):
    bmpImage = Image.open(imagePath)
    newPath = StoreFolder + "\\" +imagePath
    bmpImage.save(newPath, "BMP")
    setWallpaperFromBMP(newPath)


def setWallpaperFromBMP(imagepath):
    print imagepath
    k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") 
    win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,imagepath, 1+2)


if __name__ == '__main__' :
    data = connect_Net('http://cn.bing.com/?mkt=zh-CN')
    picUrl = get_DailyPicUrl(data.decode('utf-8'))
    picName = download_DailyPic(picUrl)
    setWallPaper(picName)

你可能感兴趣的:(python)