Python实现壁纸下载与轮换


Posted in Python onOctober 19, 2020

准备

下载安装Python3

官网下载即可,选择合适的版本:https://www.python.org/downloads/
安装一直下一步即可,记得勾选添加到环境变量。

安装pypiwin32

执行设置壁纸操作需要调用Windows系统的API,需要安装pypiwin32,控制台执行如下命令:

pip install pypiwin32

工作原理

两个线程,一个用来下载壁纸,一个用来轮换壁纸。每个线程内部均做定时处理,通过在配置文件中配置的等待时间来实现定时执行的功能。

壁纸下载线程

简易的爬虫工具,查询目标壁纸网站,过滤出有效连接,逐个遍历下载壁纸。

壁纸轮换线程

遍历存储壁纸的目录,随机选择一张壁纸路径,并使用pypiwin32库设置壁纸。

部分代码

线程创建与配置文件读取

def main():
  # 加载现有配置文件
  conf = configparser.ConfigParser()
  # 读取配置文件
  conf.read("conf.ini")
  # 读取配置项目
  search = conf.get('config', 'search')
  max_page = conf.getint('config','max_page')
  loop = conf.getint('config','loop')
  download = conf.getint('config','download')
  
  # 壁纸轮换线程
  t1 = Thread(target=loop_wallpaper,args=(loop,))
  t1.start()

  # 壁纸下载线程
  t2 = Thread(target=download_wallpaper,args=(max_page,search,download))
  t2.start()

遍历图片随机设置壁纸

def searchImage():
  # 获取壁纸路径
  imagePath = os.path.abspath(os.curdir) + '\images'
  if not os.path.exists(imagePath):
    os.makedirs(imagePath)
  # 获取路径下文件
  files = os.listdir(imagePath)
  # 随机生成壁纸索引
  if len(files) == 0:
    return
  index = random.randint(0,len(files)-1)
  for i in range(0,len(files)):
    path = os.path.join(imagePath,files[i])
    # if os.path.isfile(path):
    if i == index:
      if path.endswith(".jpg") or path.endswith(".bmp"):
        setWallPaper(path)
      else:
        print("不支持该类型文件")

设置壁纸

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)

壁纸查询链接过滤

def crawl(page,search):
  # 1\. 进入壁纸查询页面
  hub_url = 'https://wallhaven.cc/search?q=' + search + '&sorting=random&page=' + str(page)
  res = requests.get(hub_url)
  html = res.text

  # 2\. 获取链接
  ## 2.1 匹配 'href'
  links = re.findall(r'href=[\'"]?(.*?)[\'"\s]', html)
  print('find links:', len(links))
  news_links = []
  ## 2.2 过滤需要的链接
  for link in links:
    if not link.startswith('https://wallhaven.cc/w/'):
      continue
    news_links.append(link)
  print('find news links:', len(news_links))
  # 3\. 遍历有效链接进入详情
  for link in news_links:
    html = requests.get(link).text
    fing_pic_url(link, html)
  print('下载成功,当前页码:'+str(page));

图片下载

def urllib_download(url):
  #设置目录下载图片
  robot = './images/'
  file_name = url.split('/')[-1]
  path = robot + file_name
  if os.path.exists(path):
    print('文件已经存在')
  else:
    url=url.replace('\\','')
    print(url)
    r=requests.get(url,timeout=60)
    r.raise_for_status()
    r.encoding=r.apparent_encoding
    print('准备下载')
    if not os.path.exists(robot):
      os.makedirs(robot)
    with open(path,'wb') as f:
      f.write(r.content)
      f.close()
      print(path+' 文件保存成功')

import部分

import re
import time
import requests
import os
import configparser
import random
import tldextract #pip install tldextract
import win32api, win32gui, win32con
from threading import Thread

完整代码请查看GitHub:https://github.com/codernice/wallpaper

知识点

  • threading:多线程,这里用来创建壁纸下载和壁纸轮换两个线程。
  • requests:这里用get获取页面,并获取最终的壁纸链接
  • pypiwin32:访问windows系统API的库,这里用来设置壁纸。
  • configparser:配置文件操作,用来读取线程等待时间和一些下载配置。
  • os:文件操作,这里用来存储文件,遍历文件,获取路径等。

作者:华丽的码农
邮箱:codernice@163.com
个人博客:https://www.codernice.top
GitHub:https://github.com/codernice

以上就是Python实现壁纸下载与轮换的详细内容,更多关于python 壁纸下载与轮换的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
跟老齐学Python之print详解
Sep 28 Python
基于python的Tkinter实现一个简易计算器
Dec 31 Python
全面理解Python中self的用法
Jun 04 Python
Django项目中包含多个应用时对url的配置方法
May 30 Python
PyQt5 窗口切换与自定义对话框的实例
Jun 20 Python
python自动化测试之如何解析excel文件
Jun 27 Python
Python中pymysql 模块的使用详解
Aug 12 Python
python中的数组赋值与拷贝的区别详解
Nov 26 Python
在Django下创建项目以及设置settings.py教程
Dec 03 Python
pytorch 中pad函数toch.nn.functional.pad()的用法
Jan 08 Python
Python如何在单元测试中给对象打补丁
Aug 03 Python
使用pandas生成/读取csv文件的方法实例
Jul 09 Python
Python调用REST API接口的几种方式汇总
Oct 19 #Python
Python爬虫抓取论坛关键字过程解析
Oct 19 #Python
python MD5加密的示例
Oct 19 #Python
python Yaml、Json、Dict之间的转化
Oct 19 #Python
Python pip 常用命令汇总
Oct 19 #Python
Python环境使用OpenCV检测人脸实现教程
Oct 19 #Python
python Tornado框架的使用示例
Oct 19 #Python
You might like
傻瓜化配置PHP环境――Appserv
2006/12/13 PHP
php5新改动之短标记启用方法
2008/09/11 PHP
一些php技巧与注意事项分析
2011/02/03 PHP
php递归删除目录下的文件但保留的实例分享
2014/05/10 PHP
PHP学习笔记(一) 简单了解PHP
2014/08/04 PHP
php实现的DateDiff和DateAdd时间函数代码分享
2014/08/16 PHP
PHP中list()函数用法实例简析
2016/01/08 PHP
PHP实现针对日期,月数,天数,周数,小时,分,秒等的加减运算示例【基于strtotime】
2017/04/19 PHP
PHP对称加密算法(DES/AES)类的实现代码
2017/11/14 PHP
在thinkphp5.0路径中实现去除index.php的方式
2019/10/16 PHP
js和jquery对dom节点的操作(创建/追加)
2013/04/21 Javascript
js 去掉空格实例 Trim() LTrim() RTrim()
2014/01/07 Javascript
javascript中数组(Array)对象和字符串(String)对象的常用方法总结
2016/12/15 Javascript
100多个基础常用JS函数和语法集合大全
2017/02/16 Javascript
基于JavaScript实现拖动滑块效果
2017/02/16 Javascript
新手vue构建单页面应用实例代码
2017/09/18 Javascript
React倒计时功能实现代码——解耦通用
2020/09/18 Javascript
Python中下划线的使用方法
2015/03/27 Python
Python下使用Psyco模块优化运行速度
2015/04/05 Python
python爬虫之xpath的基本使用详解
2018/04/18 Python
Python学习笔记之视频人脸检测识别实例教程
2019/03/06 Python
Python进程,多进程,获取进程id,给子进程传递参数操作示例
2019/10/11 Python
PYTHON发送邮件YAGMAIL的简单实现解析
2019/10/28 Python
keras实现基于孪生网络的图片相似度计算方式
2020/06/11 Python
Python脚本破解压缩文件口令实例教程(zipfile)
2020/06/14 Python
详解Python GUI编程之PyQt5入门到实战
2020/12/10 Python
Python 将代码转换为可执行文件脱离python环境运行(步骤详解)
2021/01/25 Python
详解使用HTML5 Canvas创建动态粒子网格动画
2016/12/14 HTML / CSS
KIKO美国官网:意大利的平价彩妆品牌
2017/05/16 全球购物
行政经理岗位职责
2013/11/09 职场文书
代理商会议邀请函
2014/01/27 职场文书
潘婷洗发水广告词
2014/03/14 职场文书
公司租房协议书
2014/10/14 职场文书
建国大业观后感800字
2015/06/01 职场文书
狼牙山五壮士观后感
2015/06/09 职场文书
聘任书格式及范文
2015/09/21 职场文书