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 相关文章推荐
下载给定网页上图片的方法
Feb 18 Python
Windows中使用wxPython和py2exe开发Python的GUI程序的实例教程
Jul 11 Python
Python自动化测试ConfigParser模块读写配置文件
Aug 15 Python
Python Paramiko模块的安装与使用详解
Nov 18 Python
详解 Python 读写XML文件的实例
Aug 02 Python
python下载文件记录黑名单的实现代码
Oct 24 Python
python使用threading获取线程函数返回值的实现方法
Nov 15 Python
Python对多属性的重复数据去重实例
Apr 18 Python
Python实现定期检查源目录与备份目录的差异并进行备份功能示例
Feb 27 Python
Python3.5迭代器与生成器用法实例分析
Apr 30 Python
django 快速启动数据库客户端程序的方法示例
Aug 16 Python
python for循环赋值问题
Jun 03 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 cli 小技巧
2013/06/03 PHP
mongo Table类文件 获取MongoCursor(游标)的实现方法分析
2013/07/01 PHP
php的sprintf函数的用法 控制浮点数格式
2014/02/14 PHP
PHP实现微信图片上传到服务器的方法示例
2017/06/29 PHP
PHP实现打包zip并下载功能
2018/06/12 PHP
Some tips of wmi scripting in jscript (1)
2007/04/03 Javascript
javascript正则表达式使用replace()替换手机号的方法
2015/01/19 Javascript
JS实现消息来时让网页标题闪动效果的方法
2016/04/20 Javascript
javascript小数精度丢失的完美解决方法
2016/05/31 Javascript
jQuery实现定位滚动条位置
2016/08/05 Javascript
浅谈JS中的!=、== 、!==、===的用法和区别
2016/09/24 Javascript
使用Vue.js创建一个时间跟踪的单页应用
2016/11/28 Javascript
React Native 图片查看组件的方法
2018/03/01 Javascript
详解angular如何调用HTML字符串的方法
2018/06/30 Javascript
对angularJs中$sce服务安全显示html文本的实例
2018/09/30 Javascript
vue2.0 如何在hash模式下实现微信分享
2019/01/22 Javascript
vue使用高德地图点击下钻上浮效果的实现思路
2019/10/12 Javascript
Vue插件之滑动验证码用法详解
2020/04/05 Javascript
JS实现小米轮播图
2020/09/21 Javascript
Nuxt pages下不同的页面对应layout下的页面布局操作
2020/11/05 Javascript
[02:32]DOTA2英雄基础教程 祸乱之源
2013/12/23 DOTA
Python实现的检测网站挂马程序
2014/11/30 Python
在Python的Django框架中更新数据库数据的方法
2015/07/17 Python
详解Python用户登录接口的方法
2019/04/17 Python
使用python对多个txt文件中的数据进行筛选的方法
2019/07/10 Python
django 使用全局搜索功能的实例详解
2019/07/18 Python
python新手学习可变和不可变对象
2020/06/11 Python
为什么称python为胶水语言
2020/06/16 Python
详解WebSocket跨域问题解决
2018/08/06 HTML / CSS
罗技英国官方网站:Logitech UK
2020/11/03 全球购物
旅游专业职业生涯规划范文
2014/01/13 职场文书
2014年综合治理工作总结
2014/11/20 职场文书
财务统计员岗位职责
2015/04/14 职场文书
沂蒙六姐妹观后感
2015/06/08 职场文书
信息技术国培研修日志
2015/11/13 职场文书
SQL Server中的逻辑函数介绍
2022/05/25 SQL Server