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判断字符串是否包含子字符串的方法
Mar 24 Python
Python实现高效求解素数代码实例
Jun 30 Python
R vs. Python 数据分析中谁与争锋?
Oct 18 Python
Python实现EXCEL表格的排序功能示例
Jun 25 Python
django-allauth入门学习和使用详解
Jul 03 Python
python导入不同目录下的自定义模块过程解析
Nov 18 Python
python 变量初始化空列表的例子
Nov 28 Python
pytorch标签转onehot形式实例
Jan 02 Python
python实现全排列代码(回溯、深度优先搜索)
Feb 26 Python
Python迭代器Iterable判断方法解析
Mar 16 Python
VScode连接远程服务器上的jupyter notebook的实现
Apr 23 Python
Pycharm同步远程服务器调试的方法步骤
Nov 04 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 采集程序原理分析篇
2010/03/05 PHP
PHP实现的方程求解示例分析
2016/11/11 PHP
php file_get_contents取文件中数组元素的方法
2017/04/01 PHP
laravel orm 关联条件查询代码
2019/10/21 PHP
jquery.fileEveryWhere.js 一个跨浏览器的file显示插件
2011/10/24 Javascript
JavaScript中的正则表达式简明总结
2014/04/04 Javascript
nodejs教程之环境安装及运行
2014/11/21 NodeJs
jQuery中:eq()选择器用法实例
2014/12/29 Javascript
JQuery插件ajaxfileupload.js异步上传文件实例
2015/05/19 Javascript
JavaScript中调用函数的4种方式代码实例
2015/07/08 Javascript
jQuery实现可编辑的表格实例讲解(2)
2015/09/17 Javascript
Javascript中的几种继承方式对比分析
2016/03/22 Javascript
如何检测JavaScript的各种类型
2016/07/30 Javascript
使用vue.js实现联动效果的示例代码
2017/01/10 Javascript
JavaScript使用链式方法封装jQuery中CSS()方法示例
2017/04/07 jQuery
基于js的变量提升和函数提升(详解)
2017/09/17 Javascript
基于vue实现分页效果
2017/11/06 Javascript
vue分页器组件编写方法详解
2019/06/28 Javascript
解决安装python库时windows error5 报错的问题
2018/10/21 Python
python 实现语音聊天机器人的示例代码
2018/12/02 Python
详解Python数据分析--Pandas知识点
2019/03/23 Python
python画图——实现在图上标注上具体数值的方法
2019/07/08 Python
python 模拟银行转账功能过程详解
2019/08/06 Python
python发qq消息轰炸虐狗好友思路详解(完整代码)
2020/02/15 Python
解决使用python print打印函数返回值多一个None的问题
2020/04/09 Python
Python迭代器协议及for循环工作机制详解
2020/07/14 Python
Ralph Lauren拉夫·劳伦美国官网:带有浓郁美国气息的高品味时装品牌
2017/11/01 全球购物
新闻专业本科生的自我评价分享
2013/11/20 职场文书
天猫某品牌专卖店运营计划书
2014/03/21 职场文书
学校消防安全责任书
2014/07/23 职场文书
幼儿生日活动方案
2014/08/27 职场文书
财务工作疏忽检讨书
2014/09/11 职场文书
教师工作失职检讨书
2014/09/18 职场文书
股东出资证明书范例
2014/10/04 职场文书
《葡萄沟》教学反思
2016/02/23 职场文书
Nginx已编译的nginx-添加新模块
2021/04/01 Servers