Python实现设置windows桌面壁纸代码分享


Posted in Python onMarch 28, 2015

每天换一个壁纸,每天好心情。

# -*- 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 "解析图片地址出错,请检查正则表达式是否正确"
      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()
Python 相关文章推荐
使用Python的Twisted框架编写简单的网络客户端
Apr 16 Python
python字符串,数值计算
Oct 05 Python
python中字符串类型json操作的注意事项
May 02 Python
使用python爬虫实现网络股票信息爬取的demo
Jan 05 Python
Python实现加载及解析properties配置文件的方法
Mar 29 Python
Python requests发送post请求的一些疑点
May 20 Python
解决seaborn在pycharm中绘图不出图的问题
May 24 Python
python根据txt文本批量创建文件夹
Dec 08 Python
深入了解Django中间件及其方法
Jul 26 Python
python爬虫 urllib模块发起post请求过程解析
Aug 20 Python
python GUI库图形界面开发之PyQt5状态栏控件QStatusBar详细使用方法实例
Feb 28 Python
使用Python FastAPI构建Web服务的实现
Jun 08 Python
Python中的类与对象之描述符详解
Mar 27 #Python
深入理解Javascript中的this关键字
Mar 27 #Python
Python运用于数据分析的简单教程
Mar 27 #Python
Python中下划线的使用方法
Mar 27 #Python
利用Python和OpenCV库将URL转换为OpenCV格式的方法
Mar 27 #Python
python根据出生年份简单计算生肖的方法
Mar 27 #Python
python实现根据月份和日期得到星座的方法
Mar 27 #Python
You might like
php获取文件内容最后一行示例
2014/01/09 PHP
PHP去掉json字符串中的反斜杠\及去掉双引号前的反斜杠
2015/09/30 PHP
PHP自定义错误用法示例
2016/09/28 PHP
Redis使用Eval多个键值自增的操作实例
2016/11/04 PHP
一个实用的php验证码类
2017/07/06 PHP
PHP程序员必须知道的两种日志实例分析
2020/05/14 PHP
PHP实现简单注册登录系统
2020/12/28 PHP
javascript显示用户停留时间的简单实例
2013/08/05 Javascript
解决Jquery向页面append新元素之后事件的绑定问题
2015/03/16 Javascript
Angularjs在初始化未完毕时出现闪烁问题的解决方法分析
2016/08/05 Javascript
JS中的hasOwnProperty()、propertyIsEnumerable()和isPrototypeOf()
2016/08/11 Javascript
原生js实现秒表计时器功能
2017/02/16 Javascript
JS获取url参数,JS发送json格式的POST请求方法
2018/03/29 Javascript
微信小程序如何实现五星评价功能
2019/10/15 Javascript
vue.js实现三级菜单效果
2019/10/19 Javascript
详解vue页面首次加载缓慢原因及解决方案
2019/11/06 Javascript
javascript实现拖拽碰撞检测
2020/03/12 Javascript
Vue ElementUI实现:限制输入框只能输入正整数的问题
2020/07/31 Javascript
[03:41]2018完美盛典-《Fight With Us》
2018/12/16 DOTA
详谈Python2.6和Python3.0中对除法操作的异同
2017/04/28 Python
python 求一个列表中所有元素的乘积实例
2019/06/11 Python
pyqt 实现QlineEdit 输入密码显示成圆点的方法
2019/06/24 Python
Pandas之排序函数sort_values()的实现
2019/07/09 Python
Python下opencv图像阈值处理的使用笔记
2019/08/04 Python
Python文件路径名的操作方法
2019/10/30 Python
HTML高亮关键字的实现代码
2018/10/22 HTML / CSS
第二层交换机和路由器的区别?第三层交换机和路由器的区别?
2013/05/23 面试题
50岁生日感言
2014/01/23 职场文书
工厂门卫岗位职责范本
2014/04/04 职场文书
竞选村长演讲稿
2014/04/28 职场文书
民主评议党员自我评价材料
2014/09/18 职场文书
放牛班的春天观后感
2015/06/01 职场文书
红白喜事主持词
2015/07/06 职场文书
中小学教师继续教育心得体会
2016/01/19 职场文书
Java图书管理系统,课程设计必用(源码+文档)
2021/06/30 Java/Android
纯html+css实现Element loading效果
2021/08/02 HTML / CSS