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实现递归遍历文件夹并删除文件
Apr 18 Python
关于python的bottle框架跨域请求报错问题的处理方法
Mar 19 Python
wxPython实现窗口用图片做背景
Apr 25 Python
Python实现的朴素贝叶斯算法经典示例【测试可用】
Jun 13 Python
Python中使用遍历在列表中添加字典遇到的坑
Feb 27 Python
pytorch 输出中间层特征的实例
Aug 17 Python
Python 解决OPEN读文件报错 ,路径以及r的问题
Dec 19 Python
Python改变对象的字符串显示的方法
Aug 01 Python
Python paramiko使用方法代码汇总
Nov 20 Python
python爬虫框架feapde的使用简介
Apr 20 Python
python 常用的异步框架汇总整理
Jun 18 Python
Python 装饰器(decorator)常用的创建方式及解析
Apr 24 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
thinkPHP5.0框架整体架构总览【应用,模块,MVC,驱动,行为,命名空间等】
2017/03/25 PHP
基于laravel belongsTo使用详解
2019/10/18 PHP
js获取TreeView控件选中节点的Text和Value值的方法
2012/11/24 Javascript
JS基于Ajax实现的网页Loading效果代码
2015/10/27 Javascript
体验jQuery和AngularJS的不同点及AngularJS的迷人之处
2016/02/02 Javascript
基于bootstrap实现广告轮播带图片和文字效果
2016/07/22 Javascript
基于JavaScript实现的顺序查找算法示例
2017/04/14 Javascript
web前端页面生成exe可执行文件的方法
2018/02/08 Javascript
怎么使用javascript深度拷贝一个数组
2019/06/06 Javascript
AutoJs实现刷宝短视频的思路详解
2020/05/22 Javascript
vue实现页面切换滑动效果
2020/06/29 Javascript
JS实现放大镜效果
2020/09/21 Javascript
python批量提交沙箱问题实例
2014/10/08 Python
在Python下进行UDP网络编程的教程
2015/04/29 Python
简单介绍Python中的decode()方法的使用
2015/05/18 Python
python自动发邮件库yagmail的示例代码
2018/02/23 Python
利用Python代码实现数据可视化的5种方法详解
2018/03/25 Python
Python实现的简单排列组合算法示例
2018/07/04 Python
django解决跨域请求的问题详解
2019/01/20 Python
PyQt5 QListWidget选择多项并返回的实例
2019/06/17 Python
使用遗传算法求二元函数的最小值
2020/02/11 Python
Python打包工具PyInstaller的安装与pycharm配置支持PyInstaller详细方法
2020/02/27 Python
Python datetime模块使用方法小结
2020/06/18 Python
浅谈django框架集成swagger以及自定义参数问题
2020/07/07 Python
python实现学生信息管理系统源码
2021/02/22 Python
柒牌官方商城:中国男装优秀品牌
2017/06/30 全球购物
Wedgwood美国官网:英国骨瓷,精美礼品及家居装饰
2018/02/17 全球购物
伦敦一家领先的精品零售商:IRIS Fashion
2019/05/24 全球购物
阿拉伯时尚购物网站:Nisnass
2021/02/07 全球购物
C语言怎样定义和声明全局变量和函数最好
2013/11/26 面试题
口腔工艺技术专业毕业生自荐信
2013/09/27 职场文书
教学个人的自我评价分享
2014/02/16 职场文书
机电专业大学生职业规划书范文
2014/02/25 职场文书
手机银行营销方案
2014/03/14 职场文书
家长给老师的感谢信
2015/01/20 职场文书
详解CSS中的特指度和层叠问题
2021/07/15 HTML / CSS