Python实现壁纸自动下载与定时轮换

Felix
Felix
发布时间:2026-10-14 | 4人浏览过
原创

本文介绍如何使用Python实现壁纸的自动下载与定时轮换功能。通过安装pypiwin32调用Windows API,结合threading多线程处理下载与轮换任务,利用requests和configparser实现配置化管理。教程涵盖环境搭建、核心代码逻辑及完整源码获取方式,帮助用户轻松打造个性化动态桌面。

准备工作

准备工作

安装Python3环境

前往Python官网下载对应操作系统的安装包,建议选择稳定版本。安装过程中请确保勾选“Add Python to PATH”选项,以便将Python添加到系统环境变量中,随后一路点击下一步即可完成安装。

安装pypiwin32依赖库

为了在Windows系统中执行设置壁纸的操作,必须调用Windows系统的底层API,因此需要安装pypiwin32库。请在控制台(CMD或PowerShell)中执行以下命令进行安装:


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("不支持该类型文件")

调用Windows API设置壁纸的具体代码


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 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模块:用于发送HTTP GET请求获取网页内容,并从中解析出最终的壁纸图片链接。
  • pypiwin32模块:用于访问Windows系统API,此处主要利用其接口来修改系统注册表及调用SystemParametersInfo函数以设置壁纸。
  • configparser模块:用于处理配置文件(如ini格式),主要用来读取线程执行的等待时间间隔及其他下载相关配置参数。
  • os模块:用于常规文件操作,包括创建存储目录、遍历目录获取文件列表、判断文件是否存在及获取文件路径等。

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

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

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表