在上次弄得自动爬取壁纸的基础上,本人是一个喜欢经常换壁纸的小白,于是用强大的python编写了一款自动定时更换壁纸的代码,分享给有需要的人。
实现这个功能其实很简单,利用上一次贴抓到的壁纸存放的网络地址
urls = ['http://joyoncloud.com/wallpaper/img_detail/wwide/big/','http://joyoncloud.com/wallpaper/img_detail/alphawcc/anime_girl/toplist1y/big/','http://joyoncloud.com/wallpaper/img_detail/wpup/big/']
利用xpath抓取的每个图片实际存放的地址
links = html.xpath('//a/@href')
然后存储到wall列表中
wall.append(urllink)
然后利用随机函数进行随机选取其中一个地址进行请求,下载
url = random.sample(wall,1)[0]res = session.get(url)
with open('link.jpg', 'wb') as f:
f.write(res.content)
然后医用网上當到的设置壁纸的函数
def setWallpaperFrom(imagepath): k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\Desktop",0,win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2")
win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,imagepath, 1+2)
自动进行壁纸设置。
代码见:
import requests
from lxml import etree
import os
import time
import random
import win32api,win32con,win32gui
session = requests.Session()
# urls = ['http://joyoncloud.com/wallpaper/img_detail/jtix/big/','http://joyoncloud.com/wallpaper/img_detail/jtix/big2/','http://joyoncloud.com/wallpaper/img_detail/wwide/big/','http://joyoncloud.com/wallpaper/img_detail/alphawcc/anime_girl/toplist1y/big/','http://joyoncloud.com/wallpaper/img_detail/wpup/big/']
urls = ['http://joyoncloud.com/wallpaper/img_detail/wwide/big/','http://joyoncloud.com/wallpaper/img_detail/alphawcc/anime_girl/toplist1y/big/','http://joyoncloud.com/wallpaper/img_detail/wpup/big/']
wall = []
for url in urls:
try:
res = session.get(url).text
html = etree.HTML(res)
links = html.xpath('//a/@href')
for link in links:
try:
# if 'wallhaven'in link:
urllink = url + link
wall.append(urllink)
except:
pass
except:
pass
def setWallpaperFrom(imagepath):
k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\Desktop",0,win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") #2拉伸适应桌面,0桌面居中
win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,imagepath, 1+2)
while True:
try:
url = random.sample(wall,1)[0]
res = session.get(url)
with open('link.jpg', 'wb') as f:
f.write(res.content)
setWallpaperFrom('link.jpg')
os.remove('link.jpg')
time.sleep(300)
except:
continue
网友评论