介绍

python基于selenium2中的webdriver以及pywin32模块,定时从指定网站随机下载壁纸,然后更新桌面壁纸的实现。

代码

首先定义一个基于selenium的webdriver的无UI的Chrome浏览器对象,–headless参数定义为无界面,–disable-gpu关闭gpu是为了解决chrome卡的bug。

def __init__(self, url):self.url = urlself.isFirst = Trueoptions = Options()options.add_argument('--headless')options.add_argument('--disable-gpu')self.driver = webdriver.Chrome(chrome_options=options)

然后就是要去指定网站随机获取图。在这里,使用set_page_load_timeout函数设置页面加载超时为30秒,如果30秒加载没有完成,则直接超时退出。第一次加载页面,使用get函数来加载,当已经加载过以后,则直接用refresh函数刷新页面即可。WebDriverWaituntil组合使用表示,最多等待10秒,直接到页面找到指定元素才返回,如果超时10秒还没有找到指定元素,则抛出TimeoutException异常,如果页面加载完成还没有找到指定元素则抛出NoSuchElementException异常。find_element_by_xpath用来查找页面中的指定元素,get_attribute函数是获取当前元素指定属性的值。

def run(self):self.driver.set_page_load_timeout(30)if self.isFirst:self.driver.get(self.url)self.isFirst = Falseelse:self.driver.refresh()print(self.driver.title)try:link = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH,'//*[@id="thumbs"]/section[1]/ul/li[1]/figure/a')))print(link.get_attribute('href'))self.driver.get(link.get_attribute('href'))print(self.driver.title)img = self.driver.find_element_by_xpath('//*[@id="wallpaper"]')print(img.get_attribute('src'))self.download(img.get_attribute('src'))except TimeoutException:traceback.print_exc()passexcept NoSuchElementException:traceback.print_exc()pass

使用requests模块的get函数下载图片,当返回的status_code等于200表示成功,其它表示失败。下载成功以后,把图片写入程序工作目录的desktop目录下,没有则创建。

def download(self, imageUrl):res = requests.get(imageUrl)if (res.status_code == 200):currentPath = os.getcwd()desktopPath = os.path.join(currentPath, 'desktop')if (not os.path.exists(desktopPath)):os.mkdir(desktopPath)filename = imageUrl.rsplit('/')[-1]fpath = os.path.join(desktopPath, filename)print(fpath)with open(fpath, "wb+") as f:f.write(res.content)self.jpgToBmp(fpath)else:print('status_code = %d' % res.status_code)

最后则是把下载的图片设置成桌面壁纸,这里用到了pywin32模块。直接操作注册表,设置桌面壁纸的样式,然后调用SystemParametersInfo函数设置桌面壁纸并更新桌面,壁纸则设置完成。

def setWallpaper(self, img):regKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop",0, win32con.KEY_SET_VALUE)# 0=居中 1=平铺 2=拉伸win32api.RegSetValueEx(regKey, "WallpaperStyle",0, win32con.REG_SZ, "2")# 0=居中 1=平铺 2=拉伸win32api.RegSetValueEx(regKey, "TileWallpaper",0, win32con.REG_SZ, "0")win32api.RegCloseKey(regKey)# 设置桌面壁纸并更新win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img, win32con.SPIF_SENDWININICHANGE)

Note:早期系统不支持jpg文件设置成桌面壁纸,所以在这里使用Image模块把jpg文件转换成bmp位图,再把转换以后的图片设置成壁纸。在转换之前,先把之前转换的bmp位图都删除,防止占用硬盘空间(当然你的硬盘大就无所谓了)。

def deleteBmpFile(self, path):for name in os.listdir(path):filePath = os.path.join(path, name)if (filePath.endswith(".bmp")):os.remove(filePath)def jpgToBmp(self, img):imgDir = os.path.dirname(img)self.deleteBmpFile(imgDir)jpgImage = Image.open(img)fileName = img.split('\\')[-1]prefixName = fileName.split('.')[0]bmpFilename = prefixName + '.bmp'bmpImage = os.path.join(imgDir, bmpFilename)jpgImage.save(bmpImage, "BMP")self.setWallpaper(bmpImage)

完整代码如下,这里的实现设置成每10分钟从网站下载一次图片设置成桌面壁纸并循环处理,同时并没有删除每次下载的jpg图片,只是删除了bmp位图。

# -*- coding: utf-8 -*-
import os
import time
import tracebackimport requests
import win32con
from PIL import Imageimport win32api
import win32gui
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWaitclass WallPaper:def __init__(self, url):self.url = urlself.isFirst = Trueoptions = Options()options.add_argument('--headless')options.add_argument('--disable-gpu')self.driver = webdriver.Chrome(chrome_options=options)def deleteBmpFile(self, path):for name in os.listdir(path):filePath = os.path.join(path, name)if (filePath.endswith(".bmp")):os.remove(filePath)def jpgToBmp(self, img):imgDir = os.path.dirname(img)self.deleteBmpFile(imgDir)jpgImage = Image.open(img)fileName = img.split('\\')[-1]prefixName = fileName.split('.')[0]bmpFilename = prefixName + '.bmp'bmpImage = os.path.join(imgDir, bmpFilename)jpgImage.save(bmpImage, "BMP")self.setWallpaper(bmpImage)def setWallpaper(self, img):regKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop",0, win32con.KEY_SET_VALUE)# 0=居中 1=平铺 2=拉伸win32api.RegSetValueEx(regKey, "WallpaperStyle",0, win32con.REG_SZ, "2")# 0=居中 1=平铺 2=拉伸win32api.RegSetValueEx(regKey, "TileWallpaper",0, win32con.REG_SZ, "0")win32api.RegCloseKey(regKey)# 设置桌面壁纸并更新win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img, win32con.SPIF_SENDWININICHANGE)def download(self, imageUrl):res = requests.get(imageUrl)if (res.status_code == 200):currentPath = os.getcwd()desktopPath = os.path.join(currentPath, 'desktop')if (not os.path.exists(desktopPath)):os.mkdir(desktopPath)filename = imageUrl.rsplit('/')[-1]fpath = os.path.join(desktopPath, filename)print(fpath)with open(fpath, "wb+") as f:f.write(res.content)self.jpgToBmp(fpath)else:print('status_code = %d' % res.status_code)def run(self):self.driver.set_page_load_timeout(30)if self.isFirst:self.driver.get(self.url)self.isFirst = Falseelse:self.driver.refresh()print(self.driver.title)try:link = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH,'//*[@id="thumbs"]/section[1]/ul/li[1]/figure/a')))print(link.get_attribute('href'))self.driver.get(link.get_attribute('href'))print(self.driver.title)img = self.driver.find_element_by_xpath('//*[@id="wallpaper"]')print(img.get_attribute('src'))self.download(img.get_attribute('src'))except TimeoutException:traceback.print_exc()passexcept NoSuchElementException:traceback.print_exc()passdef __del__(self):self.quit()def quit(self):self.driver.quit()def close(self):self.driver.close()if __name__ == "__main__":# http://alpha.wallhaven.cc/latest# http://alpha.wallhaven.cc/toplist# http://alpha.wallhaven.cc/randomwallPaper = WallPaper('http://alpha.wallhaven.cc/random')while True:try:wallPaper.run()print('set wall paper success.')except TimeoutException:traceback.print_exc()passprint('finish, ' + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))time.sleep(10 * 60)print('finish')

总结

其实,webdriver可以用来爬取许多东西,比如大数据收集,提取等等,图片只是其中比较基本的内容,它也可以用来执行网页当中的js脚本。

python定时更换桌面壁纸相关推荐

  1. 使用python定时更换桌面壁纸

    有时候漫画网站看到了一个挺好看的壁纸,就想着换成桌面壁纸,再过几天,又看到了另一个,还想再换,这样就很麻烦,虽说网上有很多程序,但还得下载,注册登录啥的,特别麻烦,今天就教大家用python简单实现这 ...

  2. Python桌面自定义---实现定时更换桌面壁纸

    Python桌面自定义---实现定时更换桌面壁纸 1 效果 2 获取大量壁纸 3 Python代码实现定时更换壁纸 1 效果   大致效果如下,设置过定时更换壁纸的应该都知道是啥场景. 2 获取大量壁 ...

  3. python定时换桌面壁纸

    使用Python从本地文件夹中直接调取图片,自动定时更换桌面壁纸,于是试了一试,效果贼棒! import random import ctypes import time import os path ...

  4. python修改桌面壁纸_python定时更换桌面壁纸

    介绍 python基于selenium2中的webdriver以及pywin32模块,定时从指定网站随机下载壁纸,然后更新桌面壁纸的实现. 代码 首先定义一个基于selenium的webdriver的 ...

  5. WINCE6.0更换桌面壁纸和图标

    ********************************LoongEmbedded******************************** 作者:LoongEmbedded(kandi ...

  6. linux更改桌面壁纸的脚本,自动更换桌面壁纸的脚本,支持Ubuntu 18.04系统

    下面提供一个自动更换桌面壁纸的脚本,它支持Ubuntu 18.04.UbuntuKylin 18.04.Ubuntu Mate系统. 注意事项: 1.默认的壁纸通常在目录路径为/usr/share/b ...

  7. 通过快捷方式快速更换桌面壁纸(必应每日壁纸)

    通过快捷方式快速更换桌面壁纸(必应每日壁纸) 01 前言 02 正文 03 后记 01 前言 桌面壁纸,大家都懂的,换的不是壁纸,是寂寞 心情.市面上各种桌面美化软件就不提了,这里介绍一种高端非主流玩 ...

  8. 基于红帽的Linux(centOS/fedora/RHEL)gnome3.34桌面环境用命令行更换桌面壁纸

    GNOME桌面环境用命令行更换桌面壁纸 问题引入 这篇文章将向你介绍基于红帽的linux使用GNMOE桌面环境,使用命令行更改桌面壁纸的方法. 有人会问:用命令行更改壁纸岂不是无聊至极?其实并不无聊. ...

  9. 【Python】采集3万张4K超清壁纸,实现定时自动更换桌面壁纸脚本(内含完整源码)

    前言 嗨喽!大家好,这里是魔王~ 发现一个不错的壁纸网站,里面都是超高清的图片 所以,我打算把这些壁纸都采集下来,然后在做一个自动跟换桌面壁纸的脚本,这样基本上你一年都可以每天都有不重复桌面了 先来看 ...

  10. 【Python实现定时自动更换桌面壁纸脚本】采集3万张4K超清壁纸,让你的壁纸一年都不重复

    前言 发现一个不错的壁纸网站,里面都是超高清的图片 所以,我打算把这些壁纸都采集下来,然后在做一个自动跟换桌面壁纸的脚本,这样基本上你一年都可以每天都有不重复桌面了 目标地址 先来看看我们这次的受害者 ...

最新文章

  1. JSON字符串key缺少双引号的解决方法
  2. [luoguP2331] [SCOI2005]最大子矩阵(DP)
  3. zabbix mysql设置中文乱码_解决zabbix监控因php问题导致图形界面中文乱码方法
  4. 6 linux 制作raw命令_云计算网络知识学习-linux网络基础
  5. 网站能ping通 但是打不开_SEO网站建设的三要素:域名、空间、网站程序
  6. 列文伯格-马夸尔特拟合算法(Levenberg Marquardt Fitting)的C#实现
  7. vue路由(router)设置:父路由默认选中第一个子路由,切换子路由让父路由高亮不会消失
  8. 黑马程序员2022年最新软件测试学习路线
  9. 惠普打印机m226dn教程_惠普m226dn说明书
  10. uni-app,H5抽奖
  11. 学习和使用技术的4种层次
  12. InputBox接收数字,并将该数字转成int型
  13. Tc27x的MTCR与MFCR指令
  14. python3 全局热键_python3注册全局热键的实现
  15. MySQL02--高级(BTreeB+Tree、聚簇索引非聚簇索引、性能分析(Explain)、索引、sql优化)
  16. 电子书管理软件Calibre使用
  17. 关于快手小铃铛广告投放的方式
  18. winform直接控制云台_299元,246g,260mm,一天销量破万的智云最新手机云台深度评测...
  19. 企业网络搭建与应用-交换机的配置与管理
  20. 工业工程运用计算机,工业工程如何面对挑战-精选.doc

热门文章

  1. JZOJ5442【NOIP2017提高A组冲刺11.1】荒诞 三进制状压+欧拉序
  2. migration java_如何重置migration
  3. 湘潭大学 Hurry Up 三分,求凹函数的最小值问题
  4. 计算机应用基础中专起大专,17秋中国医科大学《计算机应用基础(中专起点大专)》在线作业标准100分答案...
  5. 一名交互设计师必备的知识架构
  6. Keep your Eyes on the Lane: Real-time Attention-guided Lane Detection
  7. cd 命令行进入目标文件夹
  8. Python代码画喜羊羊怎么画_卧槽!没想到,用Python竟能做五仁月饼
  9. DOORS vs DNG
  10. 如何免费下载卫星影像图