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 mysqldb连接数据库
Mar 16 Python
python中pycurl库的用法实例
Sep 30 Python
python: line=f.readlines()消除line中\n的方法
Mar 19 Python
python编辑用户登入界面的实现代码
Jul 16 Python
Django中多种重定向方法使用详解
Jul 17 Python
Python使用itchat模块实现群聊转发,自动回复功能示例
Aug 26 Python
Django app配置多个数据库代码实例
Dec 17 Python
利用pytorch实现对CIFAR-10数据集的分类
Jan 14 Python
Python 定义只读属性的实现方式
Mar 05 Python
Python matplotlib画图时图例说明(legend)放到图像外侧详解
May 16 Python
python 写函数在一定条件下需要调用自身时的写法说明
Jun 01 Python
基于Python实现视频的人脸融合功能
Jun 12 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使之能同时支持GIF和JPEG
2006/10/09 PHP
PHP+XML 制作简单的留言本 图文教程
2009/11/02 PHP
常用PHP框架功能对照表
2014/10/23 PHP
PHP实现添加购物车功能
2017/03/06 PHP
node.js抓取并分析网页内容有无特殊内容的js文件
2015/11/17 Javascript
详解AngularJS中$http缓存以及处理多个$http请求的方法
2016/02/06 Javascript
AngularJS通过$sce输出html的方法
2016/09/22 Javascript
Jquery UI实现一次拖拽多个选中的元素操作
2020/12/01 Javascript
HTML页面定时跳转方法解析(2种任选)
2016/12/22 Javascript
ES6中Array.copyWithin()函数的用法实例详解
2017/09/16 Javascript
Angular搜索 过滤 批量删除 添加 表单验证功能集锦(实例代码)
2017/10/25 Javascript
详解微信小程序input标签正则初体验
2018/08/18 Javascript
解决Vue项目打包后打开index.html页面显示空白以及图片路径错误的问题
2019/10/25 Javascript
[54:43]DOTA2-DPC中国联赛 正赛 CDEC vs Dynasty BO3 第一场 2月22日
2021/03/11 DOTA
Python的IDEL增加清屏功能实例
2017/06/19 Python
Ubuntu16.04/树莓派Python3+opencv配置教程(分享)
2018/04/02 Python
Python使用re模块正则提取字符串中括号内的内容示例
2018/06/01 Python
python3去掉string中的标点符号方法
2019/01/22 Python
解决安装python3.7.4报错Can''t connect to HTTPS URL because the SSL module is not available
2019/07/31 Python
win7下 python3.6 安装opencv 和 opencv-contrib-python解决 cv2.xfeatures2d.SIFT_create() 的问题
2019/10/24 Python
Pytorch之finetune使用详解
2020/01/18 Python
Python标准库:内置函数max(iterable, *[, key, default])说明
2020/04/25 Python
Python更换pip源方法过程解析
2020/05/19 Python
用python批量下载apk
2020/12/29 Python
UGG雪地靴荷兰官网:UGG荷兰
2016/09/09 全球购物
Luxplus丹麦:香水和个人护理折扣
2018/04/23 全球购物
优秀应届毕业生自荐信
2013/11/16 职场文书
新学期校长寄语
2014/01/18 职场文书
乌鸦喝水教学反思
2014/02/07 职场文书
2015年五四青年节演讲稿
2015/03/18 职场文书
小学教师工作总结2015
2015/04/07 职场文书
大学军训心得体会800字
2016/01/11 职场文书
《你在为谁工作》心得体会(共8篇)
2016/01/20 职场文书
MySQL 数据类型选择原则
2021/05/27 MySQL
MySQL系列之七 MySQL存储引擎
2021/07/02 MySQL
解决使用了nginx获取IP地址都是127.0.0.1 的问题
2021/09/25 Servers