python設定windows案頭壁紙的實現代碼

來源:互聯網
上載者:User

複製代碼 代碼如下:# -*- coding: UTF-8 -*-

from __future__ import unicode_literals
import Image
import datetime
import win32gui,win32con,win32api
import re
from HttpWrapper import SendRequest

StoreFolder = "c:\\dayImage"

def setWallpaperFromBMP(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") #2展開適應案頭,0案頭置中
win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,imagepath, 1+2)

def setWallPaper(imagePath):
"""
Given a path to an image, convert it to bmp and set it as wallpaper
"""
bmpImage = Image.open(imagePath)
newPath = StoreFolder + '\\mywallpaper.bmp'
bmpImage.save(newPath, "BMP")
setWallpaperFromBMP(newPath)

def getPicture():
url = "http://photography.nationalgeographic.com/photography/photo-of-the-day/"
h = SendRequest(url)
if h.GetSource():
r = re.findall('<div class="download_link"><a href="(.*?)">Download',h.GetSource())
if r:
return SendRequest(r[0]).GetSource()
else:
print "解析圖片地址出錯,請檢查Regex是否正確"
return None

def setWallpaperOfToday():
img = getPicture()
if img:
path = StoreFolder + "\\%s.jpg" % datetime.date.today()
f = open(path,"wb")
f.write(img)
f.close()
setWallPaper(path)

setWallpaperOfToday()
print 'Wallpaper set ok!'

其中的httpwrapper是我寫的一個http訪問的封裝:複製代碼 代碼如下:#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#-------------------------------------------------------------------------------
# Name: 對http訪問的封裝
#
# Author: qianlifeng
#
# Created: 10-02-2012
#-------------------------------------------------------------------------------

import base64
import urllib
import urllib2
import time
import re
import sys

class SendRequest:
"""
網頁請求增強類
SendRequest('http://xxx.com',data=dict, type='POST', auth='base',user='xxx', password='xxx')
"""
def __init__(self, url, data=None, method='GET', auth=None, user=None, password=None, cookie = None, **header):
"""
url: 請求的url,不可為空
date: 需要post的內容,必須是字典
method: Get 或者 Post,預設為Get
auth: 'base' 或者 'cookie'
user: 用於base認證的使用者名稱
password: 用於base認證的密碼
cookie: 請求附帶的cookie,一般用於登入後的認證
其他頭資訊:
e.g. referer='www.sina.com.cn'
"""

self.url = url
self.data = data
self.method = method
self.auth = auth
self.user = user
self.password = password
self.cookie = cookie

if 'referer' in header:
self.referer = header[referer]
else:
self.referer = None

if 'user-agent' in header:
self.user_agent = header[user-agent]
else:
## self.user_agent = 'Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20100101 Firefox/8.0'
self.user_agent = 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16'

self.__SetupRequest()
self.__SendRequest()

def __SetupRequest(self):

if self.url is None or self.url == '':
raise 'url 不可為空!'

#訪問方式設定
if self.method.lower() == 'post':
self.Req = urllib2.Request(self.url, urllib.urlencode(self.data))

elif self.method.lower() == 'get':
if self.data == None:
self.Req = urllib2.Request(self.url)
else:
self.Req = urllib2.Request(self.url + '?' + urllib.urlencode(self.data))

#設定認證資訊
if self.auth == 'base':
if self.user == None or self.password == None:
raise 'The user or password was not given!'
else:
auth_info = base64.encodestring(self.user + ':' + self.password).replace('\n','')
auth_info = 'Basic ' + auth_info
self.Req.add_header("Authorization", auth_info)

elif self.auth == 'cookie':
if self.cookie == None:
raise 'The cookie was not given!'
else:
self.Req.add_header("Cookie", self.cookie)

if self.referer:
self.Req.add_header('referer', self.referer)
if self.user_agent:
self.Req.add_header('user-agent', self.user_agent)

def __SendRequest(self):

try:
self.Res = urllib2.urlopen(self.Req)
self.source = self.Res.read()
self.code = self.Res.getcode()
self.head_dict = self.Res.info().dict
self.Res.close()
except:
print "Error: HttpWrapper=>_SendRequest ", sys.exc_info()[1]

def GetResponseCode(self):
"""
得到伺服器返回的狀態代碼(200表示成功,404網頁不存在)
"""
return self.code

def GetSource(self):
"""
得到網頁原始碼,需要解碼後在使用
"""
if "source" in dir(self):
return self.source
return u''

def GetHeaderInfo(self):
"""
u'得到回應標頭資訊'
"""
return self.head_dict

def GetCookie(self):
"""
得到伺服器返回的Cookie,一般用於登入後續操作
"""
if 'set-cookie' in self.head_dict:
return self.head_dict['set-cookie']
else:
return None

def GetContentType(self):
"""
得到傳回型別
"""
if 'content-type' in self.head_dict:
return self.head_dict['content-type']
else:
return None

def GetCharset(self):
"""
嘗試得到網頁的編碼
如果得不到返回None
"""
contentType = self.GetContentType()
if contentType is not None:
index = contentType.find("charset")
if index > 0:
return contentType[index+8:]
return None

def GetExpiresTime(self):
"""
得到網頁到期時間
"""
if 'expires' in self.head_dict:
return self.head_dict['expires']
else:
return None

def GetServerName(self):
"""
得到伺服器名字
"""
if 'server' in self.head_dict:
return self.head_dict['server']
else:
return None

__all__ = [SendRequest,]

if __name__ == '__main__':
b = SendRequest("http://www.baidu.com")
print b.GetSource()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.