# -*- coding: utf-8 -*-
import requests
from lxml import etree
#import re
from re import split
#bing每日高清壁纸
def downloadWallPaper():
url = "https://bing.ioliu.cn"#需要爬取图片的网页地址
#header 文件
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.47'
}
#使用headers 进行访问
response_1=requests.get(url, headers=headers)
#对获取到的网页设置编码格式
#response_1.encoding='utf-8'
#print(response_1.text)
#必应高清壁纸第一张的位置/html/body/div[3]/div[1]/div/a <a class="mark" href="/photo/BenagilCave_ZH-CN0480408879?force=home_1"></a>
#图片在网页中的位置/html/body/div[3]/div[1]/div/a/test()
tmp=response_1.text
response_1.close()
#使用xpath进行第一张高清壁纸的定位
#参考https://blog.csdn.net/lm3758/article/details/82911636
html = etree.HTML(tmp)
firstPageUrl=url+"".join(html.xpath('//html/body/div[3]/div[1]/div/a/@href'))
#第一张高清壁纸的下载链接https://bing.ioliu.cn/photo/BenagilCave_ZH-CN0480408879?force=download
firstPageDownload=firstPageUrl.split('?')[-2]+'?force=download'
file_name = split('[/?]',firstPageUrl)[-2] + '.jpg' #根据URl设定的文件名
#下载文件
print("必应今日高清壁纸下载地址为:\n",firstPageDownload,"\n")
r=requests.get(firstPageDownload,headers=headers).content
with open(file_name,"wb") as code:
code.write(r)
return file_name
#进行壁纸设置
from os.path import abspath
import win32api,win32con,win32gui
def set_wallpaper_from_bmp(bmp_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")
#修改wallpaper注册表
win32api.RegSetValueEx(reg_key,"WallPaper",0,win32con.REG_SZ,wallpaper_path)
#刷新桌面
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,wallpaper_path, win32con.SPIF_SENDWININICHANGE)
import os
if __name__=='__main__':
#获取必应第一张壁纸的文件名
file_name = downloadWallPaper()
print("文件名为:\n",file_name)
#设定为路径设置为同目录下
file_path=abspath(".")+"\\"+file_name
set_wallpaper_from_bmp(file_path)
#setWallPaper(file_name)
#强制更新注册表
# cmd = 'RunDll32.exe USER32.DLL,UpdatePerUserSystemParameters'
# res = popen(cmd)
# output_str = res.read() # 获得输出字符串
# print(output_str)
后续步骤参考 此链接
最好设置一下起始位置,图片将存在起始位置中。