python实现桌面壁纸切换功能

yipeiwu_com6年前Python基础

本文实例为大家分享了python实现桌面壁纸切换功能的具体实现方法,供大家参考,具体内容如下

大体分为两个部分

一、利用爬虫爬取壁纸

第一部分爬取图片url地址并且下载至本地
爬虫针对 http://image.so.com/ 【360壁纸写的】,如果要更换url地址自己改改

import requests
import json
import random
import os
#存放Ajax图片地址数据 
img_url_dict={}
#创建图片tmp文件夹
if not os.path.exists('image'):
  os.mkdir('image')
#爬取图片url地址
def getImgurl(root_url,sn):
  params={
    'ch': 'wallpaper',
    't1': 157,
    'sn': sn,
    'listtype': 'new',
    'temp': 1
  }
  headers={
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko)Chrome/62.0 3202.62 Safari / 537.36'
  }
  try:
    response=requests.get(root_url,params=params,headers=headers)
  except RequestException:
    return None
  data=json.loads(response.text).get('list')
  img_url_list=[]
  for item in data:
    img_url_list.append(item.get('cover_imgurl'))
  img_url_dict[sn]=img_url_list
#下载图片
def download_image(name,image_url):
  try:
    response=requests.get(image_url)
  except RequestException:
    return "图像请求出错"
  file_name='{}/{}.{}'.format('image',name,'bmp');
  with open(file_name,'wb') as file:
    file.write(response.content)
#获取随机url地址并下载至image文件夹
def get_img():
  sn=30*random.randint(1,15)
  try:
    img_url_dict[sn]
  except KeyError:
    getImgurl('http://image.so.com/zj',sn)
  index=random.randint(0,len(img_url_dict[sn])-1)
  url=img_url_dict[sn][index]
  download_image('wallpaper',url)

二、更换桌面壁纸

第二部分将下载的图片作为壁纸,间隔一定时间重新下载,再切换壁纸
这部分借用python实现windows壁纸定期更换功能

import win32api, win32gui, win32con
import time
def setWallPaper(pic):
  # open register
  regKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
  win32api.RegSetValueEx(regKey,"WallpaperStyle", 0, win32con.REG_SZ, "2")
  win32api.RegSetValueEx(regKey, "TileWallpaper", 0, win32con.REG_SZ, "0")
  # refresh screen
  win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,pic, win32con.SPIF_SENDWININICHANGE)
if __name__=='__main__':
  while True:
    get_img()
    pic='your_path/image/wallpaper.bmp'#写绝对路径
    setWallPaper(pic)
    time.sleep(6)#6s切换一次壁纸

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

取numpy数组的某几行某几列方法

这个操作在numpy数组上的操作感觉有点麻烦,但是也没办法。 例如 a = [[1,2,3], [4,5,6], [7,8,9]] 取 a 的 2 3 行, 1 2 列...

Python 模拟登陆的两种实现方法

Python 模拟登陆的两种实现方法 有时候我们的抓取项目时需要登陆到某个网站上,才能看见某些内容的,所以模拟登陆功能就必不可少了,散仙这次写的文章,主要有2个例子,一个是普通写法写的,...

Python向Excel中插入图片的简单实现方法

Python向Excel中插入图片的简单实现方法

本文实例讲述了Python向Excel中插入图片的简单实现方法。分享给大家供大家参考,具体如下: 使用Python向Excel文件中插入图片,这个功能之前学习xlwt的时候通过xlwt模...

Python中处理字符串之islower()方法的使用简介

 islower()方法判断检查字符串的所有的字符(字母)是否为小写。 语法 以下是islower()方法的语法: str.islower() 参数  ...

python直接访问私有属性的简单方法

实例化对象名._类名__私有属性名 class Flylove: price = 123 def __init__(self): self.__d...