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批量替换页眉页脚实例代码
Jan 22 Python
Pandas_cum累积计算和rolling滚动计算的用法详解
Jul 04 Python
Python logging设置和logger解析
Aug 28 Python
python实现布隆过滤器及原理解析
Dec 08 Python
Python selenium的基本使用方法分析
Dec 21 Python
python 按钮点击关闭窗口的实现
Mar 04 Python
浅谈python3 构造函数和析构函数
Mar 12 Python
Python实现一个简单的递归下降分析器
Aug 01 Python
Python接收手机短信的代码整理
Aug 02 Python
Python爬虫爬取有道实现翻译功能
Nov 27 Python
python实现猜拳游戏项目
Nov 30 Python
浅谈Python3中datetime不同时区转换介绍与踩坑
Aug 02 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
安健A254立体声随身听的分析与打磨
2021/03/02 无线电
深入PHP许愿墙模块功能分析
2013/06/25 PHP
PHP关于IE下的iframe跨域导致session丢失问题解决方法
2013/10/10 PHP
CodeIgniter基于Email类发邮件的方法
2016/03/29 PHP
同一个表单 根据要求递交到不同页面的实现方法小结
2009/08/05 Javascript
JavaScript具有类似Lambda表达式编程能力的代码(改进版)
2010/09/14 Javascript
javascript按位非运算符的使用方法
2013/11/14 Javascript
js过滤特殊字符输入适合输入、粘贴、拖拽多种情况
2014/03/22 Javascript
jQuery遍历节点树方法分析
2016/09/08 Javascript
jQuery 移动端拖拽(模块化开发,触摸事件,webpack)
2016/10/28 Javascript
JavaScript获取短信验证码(周期性)
2016/12/29 Javascript
vue.js 实现图片本地预览 裁剪 压缩 上传功能
2018/03/01 Javascript
layui获取多选框中的值方法
2018/08/15 Javascript
Vue.js 中的 v-cloak 指令及使用详解
2018/11/19 Javascript
微信小程序之事件交互操作实例分析
2018/12/03 Javascript
JS判断数组里是否有重复元素的方法小结
2019/05/21 Javascript
编写更好的JavaScript条件式和匹配条件的技巧(小结)
2019/06/27 Javascript
Vue SPA 首屏优化方案
2021/02/26 Vue.js
python快速排序代码实例
2013/11/21 Python
对python调用RPC接口的实例详解
2019/01/03 Python
Selenium获取登录Cookies并添加Cookies自动登录的方法
2020/12/04 Python
Python实现随机爬山算法
2021/01/29 Python
利用html5 canvas破解简单验证码及getImageData接口应用
2013/01/25 HTML / CSS
Sarenza德国:法国最大的时尚鞋和包包网上商店
2019/06/08 全球购物
德国户外装备、登山运动和攀岩商店:tapir store
2020/02/12 全球购物
Java面试题及答案
2012/09/08 面试题
心理健康教育心得体会
2013/12/29 职场文书
幼儿园新学期寄语
2014/01/18 职场文书
暑期培训随笔感言
2014/03/10 职场文书
工伤赔偿协议书
2014/04/15 职场文书
团队拓展活动总结
2014/08/27 职场文书
电信营业员岗位职责
2015/04/14 职场文书
责任书格式
2019/04/18 职场文书
励志语录:时光飞逝,请学会珍惜所有的人和事
2020/01/16 职场文书
goland 设置project gopath的操作
2021/05/06 Golang
Python实现为PDF去除水印的示例代码
2022/04/03 Python