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实例之wxpython中Frame使用方法
Jun 09 Python
用Python创建声明性迷你语言的教程
Apr 13 Python
Python编程中使用Pillow来处理图像的基础教程
Nov 20 Python
python爬虫入门教程--正则表达式完全指南(五)
May 25 Python
Python使用剪切板的方法
Jun 06 Python
从头学Python之编写可执行的.py文件
Nov 28 Python
Python实现朴素贝叶斯分类器的方法详解
Jul 04 Python
一行代码让 Python 的运行速度提高100倍
Oct 08 Python
对Python3中dict.keys()转换成list类型的方法详解
Feb 03 Python
pandas分组聚合详解
Apr 10 Python
Python使用re模块验证危险字符
May 21 Python
pytorch 中forward 的用法与解释说明
Feb 26 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
很温暖很温暖的Lester Young
2021/03/03 冲泡冲煮
discuz安全提问算法
2007/06/06 PHP
JS 面向对象之继承---多种组合继承详解
2016/07/10 Javascript
WEB 前端开发中防治重复提交的实现方法
2016/10/26 Javascript
关于javascript事件响应的基础语法总结(必看篇)
2016/12/26 Javascript
javascript实现多张图片左右无缝滚动效果
2017/03/22 Javascript
利用Vue实现一个markdown编辑器实例代码
2019/05/19 Javascript
JavaScript中BOM对象原理与用法分析
2019/07/09 Javascript
原生js实现瀑布流效果
2020/03/09 Javascript
js实现查询商品案例
2020/07/22 Javascript
javascript canvas实现简易时钟例子
2020/09/05 Javascript
初步介绍Python中的pydoc模块和distutils模块
2015/04/13 Python
Python中atexit模块的基本使用示例
2015/07/08 Python
简介Django框架中可使用的各类缓存
2015/07/23 Python
全面了解Python环境配置及项目建立
2016/06/30 Python
Python3使用PyQt5制作简单的画板/手写板实例
2017/10/19 Python
Python Paramiko模块的使用实际案例
2018/02/01 Python
在python中对变量判断是否为None的三种方法总结
2019/01/23 Python
python实现将文件夹内的每张图片批量分割成多张
2019/07/22 Python
python GUI库图形界面开发之PyQt5计数器控件QSpinBox详细使用方法与实例
2020/02/28 Python
tensorflow实现从.ckpt文件中读取任意变量
2020/05/26 Python
Python叠加矩形框图层2种方法及效果
2020/06/18 Python
用Python 爬取猫眼电影数据分析《无名之辈》
2020/07/24 Python
CSS3弹性盒模型flex box快速入门心得(必看篇)
2016/05/24 HTML / CSS
丝芙兰法国官网:SEPHORA法国
2016/09/01 全球购物
美国受欢迎的眼影品牌:BH Cosmetics
2016/10/25 全球购物
英国DIY汽车维修配件网站:DIY Car Service Parts
2019/08/30 全球购物
高三地理教学反思
2014/01/11 职场文书
古汉语文学求职信范文
2014/03/16 职场文书
校园标语大全
2014/06/19 职场文书
建筑安全生产目标责任书
2014/07/23 职场文书
关于青春的演讲稿500字
2014/08/22 职场文书
贫困证明书格式及范文
2014/10/15 职场文书
布达拉宫的导游词
2015/02/02 职场文书
幼儿园中班班级总结
2015/08/10 职场文书
python+opencv实现视频抽帧示例代码
2021/06/11 Python