文章目录
1 - 简述2 - 核心代码2.1 - 爬取BingImage2.2 - 设置为桌面2.3 - 设置为每日自动执行3 - 完整代码4 - 运行结果作为鄙视链底层的“脚本小子”,到处找源码然后自己修改的小菜鸟,今天记录使用Python爬取必应每日图片,保存后设置为电脑图片的小项目。
1 - 简述
本文使用Python3,爬取BingImage作为电脑桌面壁纸。
将爬取的图片以当前日期命名,存入BingImg文件夹并设置为电脑桌面(运行程序自动创建该文件夹)。
每天更换一张背景图,大部分都属佳品,用来当作壁纸十分合适。但是这个脚本只能是运行一次就设置一次。为了解决这个问题,我们可以给系统设置一个定时任务,每天触发一次。这样就可以实现每天自动更换BingImage作为电脑桌面了。
2 - 核心代码
2.1 - 爬取BingImage
def getImage(local):url = '/HPImageArchive.aspx?format=js&idx=0&n=1' # 调用的 json 文件(format=js)os.makedirs('BingImg', exist_ok=True) # 生成 BingImg 文件夹用来保存图片con = requests.get(url)content = json.loads(con.text)picUrl = '' + content['images'][0]['url']if picUrl == '':print('找不到图片!程序出错啦!')sys.exit()else:print('获取图片地址成功:' + picUrl)print('开始下载···') read = requests.get(picUrl)f = open(os.path.join('BingImg', '%s.jpg' % local), 'wb')f.write(read.content)f.close()print('下载成功!')
2.2 - 设置为桌面
def setWallPaper(pic):print('正在更新桌面背景.....')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 screenwin32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,pic, win32con.SPIF_SENDWININICHANGE)print('更新完辽!')print('-'*20)print('开心么?\n鹅鹅鹅饿鹅鹅鹅饿.....')
2.3 - 设置为每日自动执行
设置步骤:
右击“计算机”→管理→计划任务程序→创建基本任务
接下来按照指引完成设置即可。
3 - 完整代码
# 爬取今日Bing Image并设置为桌面import sysimport osimport timeimport jsonimport requestsfrom PIL import Image import win32api, win32gui, win32condef getImage(local):url = '/HPImageArchive.aspx?format=js&idx=0&n=1' # 调用的 json 文件(format=js)os.makedirs('BingImg', exist_ok=True) # 生成 BingImg 文件夹用来保存图片con = requests.get(url)content = json.loads(con.text)picUrl = '' + content['images'][0]['url']if picUrl == '':print('找不到图片!程序出错啦!')sys.exit()else:print('获取图片地址成功:' + picUrl)print('开始下载···') read = requests.get(picUrl)f = open(os.path.join('BingImg', '%s.jpg' % local), 'wb')f.write(read.content)f.close()print('下载成功!')def showImage(imgName,local):img = Image.open('%s/BingImg/%s.jpg'%(imgName,local))img.show()def setWallPaper(pic):print('正在更新桌面背景.....')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 screenwin32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,pic, win32con.SPIF_SENDWININICHANGE)print('更新完辽!')print('-'*20)print('开心么?\n鹅鹅鹅饿鹅鹅鹅饿.....')if __name__=='__main__':local = time.strftime("%Y-%m-%d") # 以当天日期命名文件imgName = os.getcwd().replace("\\","/") # 获取当前文件夹地址#print(local)getImage(local)#showImage(imgName,local)pic = '%s/BingImg/%s.jpg'%(imgName,local)# 获取图片路径setWallPaper(pic)