必应 的每日图片还是不错的,换作自己的桌面壁纸挺有意思的。
这种简单的小程序实现网络上还是很多的,但还是想亲手写一写。
把代码分享一下
# 获取必应每日图片
import os
import pathlib
import time
import urllib
from lxml import etree
import win32api,win32con,win32gui
host = "https://cn.bing.com/"
# 获取必应每日图片网络地址
def get_picture_href():
# request请求必应首页
req = urllib.request.urlopen(host)
html = req.read().decode("UTF-8")
req.close()
# 使用Xpath找出链接地址(需要安装lxml包),也可以使用正则(re)查找
selector = etree.HTML(html)
pic_href = selector.xpath('//*[@id="bgLink"]/@href')[0]
# 链接去掉后面冗长的字段
href = pic_href.split("&")[0]
# 拼接得到完整url
url = host + href
return url
# 下载图片,返回图片绝对地址
def download(url):
# 获取后缀
suffix = pathlib.Path(url).suffix
# 以时间戳命名下载图片
filename, headers = urllib.request.urlretrieve(url, "bing_pic_"+str(time.time())+suffix)
print("图片请求信息为:")
print(headers)
print("图片保存为:"+filename)
return os.path.abspath(filename)
# 更换桌面壁纸(需要安装pywin32包)
def set_wallpaper(img_path):
# 打开指定注册表路径
reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
# 最后的参数:2拉伸,0居中,6适应,10填充,0平铺
win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
# 最后的参数:1表示平铺,拉伸居中等都是0
win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")
# 刷新桌面
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img_path, win32con.SPIF_SENDWININICHANGE)
pic_url = get_picture_href()
pic_path = download(pic_url)
set_wallpaper(pic_path)
Xpath那里本来用正则re模块写就行,这样看起来直观。
要安装的模块:
pip install lxml
pip install pywin32