本教程内容为:Python定时爬取Bing每日推荐壁纸,支持设为桌面壁纸及发送飞书通知
Python源码
创建bing-Image.pyw
文件,内容如下
import requests
import json
import re
import os
import subprocess
import time
import tkinter as tk
from tkinter import messagebox
import ctypes
import sys
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
"Connection": "close",
'Content-Type': "application/json",
}
feishu_headers = {'Content-Type': 'application/json'}
def dumpBingWallpaper():
try:
# 解析 URL
n = 1
idx = 0
url = "https://www.bing.com/HPImageArchive.aspx?format=js&idx={}&n={}&mkt=zh-CN".format(idx, n)
res = requests.get(url, headers=headers)
res.raise_for_status()
res.encoding = 'utf8'
jsonData = json.loads(res.text)
uri = jsonData['images'][0]['url']
# 获取图像地址与信息
img = requests.get("https://www.bing.com/" + uri, headers=headers)
img.raise_for_status()
img_content = img.content
desc = str(jsonData['images'][0]['copyright']).split(",")[0]
dt = jsonData['images'][0]['startdate']
# 使用正则表达式匹配 "id=" 后面的部分
pattern = re.compile(r'id=([^&]+)')
match = pattern.search(uri)
if match:
# 提取匹配的字符串部分
file_path = match.group(1)
# 通过"."进行分隔,获取文件后缀
file_extension = file_path.split('.')[-1]
else:
print("No match found.")
return
folder_name = 'bing_image'
if not os.path.exists(folder_name):
# 如果不存在,则创建文件夹
os.makedirs(folder_name)
print(f"文件夹 '{folder_name}' 创建成功。")
else:
print(f"文件夹 '{folder_name}' 已经存在。")
# 输出地址
output = os.path.join(folder_name, f"{desc}_{dt}.{file_extension}")
with open(output, 'wb') as out:
out.write(img_content)
# 发送飞书通知
feishu_webhook_url = 'webhook_url'
# 构造消息
message = {
"msg_type": "interactive",
"card": {
"elements": [{
"tag": "div",
"text": {
"content": f"**图片名称:**{desc}_{dt}.{file_extension}\n**图片描述:**{jsonData['images'][0]['copyright']}",
"tag": "lark_md"
}
}, {
"actions": [{
"tag": "button",
"text": {
"content": "点击查看图片",
"tag": "lark_md"
},
"url": f"https://www.bing.com{uri}",
"type": "default",
"value": {}
}],
"tag": "action"
}],
"header": {
"title": {
"content": "Bing每日壁纸推荐",
"tag": "plain_text"
}
}
}
}
feishu_response = requests.post(feishu_webhook_url, json=message, headers=feishu_headers)
if feishu_response.status_code == 200:
print("发送通知成功")
else:
tk.messagebox.showinfo("发送通知失败", f"状态码:{feishu_response.status_code}")
sys.exit()
return f"{desc}_{dt}.{file_extension}"
except requests.RequestException as e:
tk.messagebox.showinfo("网络请求错误", f"Error:{e}")
sys.exit()
except json.JSONDecodeError as e:
tk.messagebox.showinfo("JSON解析错误", f"Error:{e}")
sys.exit()
except IOError as e:
tk.messagebox.showinfo("文件处理错误", f"Error:{e}")
sys.exit()
except Exception as e:
tk.messagebox.showinfo("未知错误", f"Error:{e}")
sys.exit()
def on_confirm():
# 确认按钮点击事件
root.destroy() # 关闭弹窗
image_name = dumpBingWallpaper()
# 显示弹窗
result2 = messagebox.askquestion("确认", "请确认是否将Bing每日推荐壁纸设置为桌面壁纸")
# 判断是否进行爬取
if result2 == 'yes':
set_wallpaper(f"bing_image/{image_name}")
def on_cancel():
# 取消按钮点击事件
root.destroy() # 关闭弹窗
print("用户选择取消,程序退出")
sys.exit() # 退出程序
def set_wallpaper(image_path):
if not os.path.isfile(image_path):
tk.messagebox.showinfo("错误", f"文件不存在:'{image_path}'")
sys.exit()
abs_path = os.path.abspath(image_path)
result = ctypes.windll.user32.SystemParametersInfoW(20, 0, abs_path, 1 | 2)
if not result:
tk.messagebox.showinfo("错误", f"{ctypes.WinError()}")
sys.exit()
root = tk.Tk()
# 隐藏主窗口
root.withdraw()
# 显示弹窗
result1 = messagebox.askquestion("确认", "请确认是否爬取Bing每日推荐壁纸")
if __name__ == "__main__":
# 判断是否进行爬取
if result1 == 'yes':
on_confirm()
else:
on_cancel()
Windows设置定时任务
按 Win + R
打开“运行”对话框。
输入 taskschd.msc
并按回车,打开任务计划程序
在任务计划程序中,点击右侧的创建基本任务
输入任务名称,点击
下一步
选择任务触发器
,这里选择每天都执行
选择开始执行时间和时间间隔,点击下一步
选择启动程序
,点击下一步
填写Python爬虫脚本文件信息,此处需要选择pythonw.exe
以去除程序执行时弹出的黑框,添加参数
选择bing-Image.pyw
文件路径,点击下一步
点击完成
实现效果: