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中映射类型(字典)操作符的概念和使用
Aug 19 Python
python模拟Django框架实例
May 17 Python
python 实现一次性在文件中写入多行的方法
Jan 28 Python
python 多线程对post请求服务器测试并发的方法
Jun 13 Python
python logging模块的使用总结
Jul 09 Python
用Python从0开始实现一个中文拼音输入法的思路详解
Jul 20 Python
使用pip安装python库的多种方式
Jul 31 Python
Spring实战之使用util:命名空间简化配置操作示例
Dec 09 Python
Python3 利用face_recognition实现人脸识别的方法
Mar 13 Python
如何基于Python爬虫爬取美团酒店信息
Nov 03 Python
如何用Python和JS实现的Web SSH工具
Feb 23 Python
Python学习开发之图形用户界面详解
Aug 23 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生成静态页面分析 模板+缓存+写文件
2009/08/17 PHP
PHP中PDO的错误处理
2011/09/04 PHP
php求正负数数组中连续元素最大值示例
2014/04/11 PHP
PHP加密解密实例分析
2015/12/25 PHP
PHP上传Excel文件导入数据到MySQL数据库示例
2016/10/25 PHP
PHP实现根据数组某个键值大小进行排序的方法
2018/03/13 PHP
php实现微信发红包功能
2018/07/13 PHP
php进程daemon化的正确实现方法
2018/09/06 PHP
Javascript Cookie读写删除操作的函数
2010/03/02 Javascript
javascript权威指南 学习笔记之变量作用域分享
2011/09/28 Javascript
jquery中获得元素尺寸和坐标的方法整理
2014/05/18 Javascript
jQuery中的height innerHeight outerHeight区别示例介绍
2014/06/15 Javascript
JavaScript合并两个数组并去除重复项的方法
2015/06/13 Javascript
对于jQuery性能的一些优化建议
2015/08/13 Javascript
js实现浮动在网页右侧的简洁QQ在线客服代码
2015/09/04 Javascript
js采用concat和sort将N个数组拼接起来的方法
2016/01/21 Javascript
javascript事件处理模型实例说明
2016/05/31 Javascript
JS跨域交互(jQuery+php)之jsonp使用心得
2016/07/01 Javascript
深入解析桶排序算法及Node.js上JavaScript的代码实现
2016/07/06 Javascript
vue + element-ui实现简洁的导入导出功能
2017/12/22 Javascript
jQuery实现仿京东防抖动菜单效果示例
2018/07/06 jQuery
[37:03]完美世界DOTA2联赛PWL S3 INK ICE vs GXR 第二场 12.16
2020/12/18 DOTA
win10下Python3.6安装、配置以及pip安装包教程
2017/10/01 Python
Python内置模块ConfigParser实现配置读写功能的方法
2018/02/12 Python
利用Python的sympy包求解一元三次方程示例
2019/11/22 Python
Python把图片转化为pdf代码实例
2020/07/28 Python
外语专业毕业生个人的自荐信
2013/11/19 职场文书
大学生村官事迹材料
2014/01/21 职场文书
环境日宣传活动总结
2014/07/09 职场文书
2014年十八届四中全会思想汇报范文
2014/10/17 职场文书
护士求职简历自我评价
2015/03/10 职场文书
导游词创作书写原则以及开场白技巧怎么学?
2019/09/25 职场文书
python调试工具Birdseye的使用教程
2021/05/25 Python
解析redis hash应用场景和常用命令
2021/08/04 Redis
Win10玩csgo闪退如何解决?Win10玩csgo闪退的解决方法
2022/07/23 数码科技
戴尔Win11系统no bootable devices found解决教程
2022/09/23 数码科技