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验证企业工商注册码
Oct 25 Python
Python中的浮点数原理与运算分析
Oct 12 Python
详解tensorflow实现迁移学习实例
Feb 10 Python
Python使用Scrapy爬虫框架全站爬取图片并保存本地的实现代码
Mar 04 Python
python3.4爬虫demo
Jan 22 Python
Django处理Ajax发送的Get请求代码详解
Jul 29 Python
Python多线程爬取豆瓣影评API接口
Oct 22 Python
利用python3 的pygame模块实现塔防游戏
Dec 30 Python
如何在python中判断变量的类型
Jul 29 Python
python生成xml时规定dtd实例方法
Sep 21 Python
python代码实现扫码关注公众号登录的实战
Nov 01 Python
python获取字符串中的email
Mar 31 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
解析argc argv在php中的应用
2013/06/24 PHP
CodeIgniter使用phpcms模板引擎
2013/11/12 PHP
WordPress中创建用户角色的相关PHP函数使用详解
2015/12/25 PHP
php实现的二分查找算法示例
2017/06/20 PHP
PHPExcel实现表格导出功能示例【带有多个工作sheet】
2018/06/13 PHP
Thinkphp5 如何隐藏入口文件index.php(URL重写)
2019/10/16 PHP
php经典趣味算法实例代码
2020/01/21 PHP
JavaScript 入门·JavaScript 具有全范围的运算符
2007/10/01 Javascript
js函数使用技巧之 setTimeout(function(){},0)
2009/02/09 Javascript
一段实现页面上的图片延时加载的js代码
2010/02/11 Javascript
JavaScript CSS修改学习第六章 拖拽
2010/02/19 Javascript
JavaScript性能优化 创建文档碎片(document.createDocumentFragment)
2010/07/13 Javascript
Extjs优化(一)删除冗余代码提高运行速度
2013/04/15 Javascript
js判断选择时间不能小于当前时间的示例代码
2013/09/24 Javascript
JS控制表格实现一条光线流动分割行的方法
2015/03/09 Javascript
JS实现控制表格行内容垂直对齐的方法
2015/03/30 Javascript
Bootstrap CSS布局之表单
2016/12/17 Javascript
小发现之浅谈location.search与location.hash的问题
2017/06/23 Javascript
在 Node.js 中使用原生 ES 模块方法解析
2017/09/19 Javascript
Bootstrap框架建立树形菜单(Tree)的实例代码
2017/10/30 Javascript
ES6 javascript中Class类继承用法实例详解
2017/10/30 Javascript
jQuery获取所有父级元素及同级元素及子元素的方法(推荐)
2018/01/21 jQuery
微信小程序语音同步智能识别的实现案例代码解析
2020/05/29 Javascript
Python中的anydbm模版和shelve模版使用指南
2015/07/09 Python
实例解析Python设计模式编程之桥接模式的运用
2016/03/02 Python
Pytorch环境搭建与基本语法
2020/06/03 Python
利用python绘制中国地图(含省界、河流等)
2020/09/21 Python
python批量检查两个对应的txt文件的行数是否一致的实例代码
2020/10/31 Python
HTML5安全介绍之内容安全策略(CSP)简介
2012/07/10 HTML / CSS
详解HTML5如何使用可选样式表为网站或应用添加黑暗模式
2020/04/07 HTML / CSS
教师竞聘演讲稿
2014/05/16 职场文书
男方婚前保证书
2015/02/28 职场文书
网络销售员岗位职责
2015/04/11 职场文书
结婚司仪主持词
2015/06/29 职场文书
Python机器学习算法之决策树算法的实现与优缺点
2021/05/13 Python
浅谈Python中的函数(def)及参数传递操作
2021/05/25 Python