import schedule
import time
import requests
from bs4 import BeautifulSoup
from datetime import datetime
# 保存最新的帖子ID
latest_post_id = None
def check_forum():
global latest_post_id
print("正在检查论坛...") # 添加日志
url = "https://bbs.z-xin.net/?sort=newest" # 更新基础链接
try:
response = requests.get(url)
response.raise_for_status() # 确保请求成功
except requests.exceptions.RequestException as e:
print(f"请求出错: {e}")
return
soup = BeautifulSoup(response.text, "html.parser")
# 初始化 posts 为一个空列表
posts = []
# 更精确地定位到帖子列表
container = (
soup.find("div", id="app")
.find("main", class_="App-content")
.find("noscript", id="flarum-content")
.find("div", class_="container")
.find("ul")
)
if container:
posts = container.find_all("li")
print(f"找到 {len(posts)} 个帖子。") # 添加日志
else:
print("未找到帖子列表。") # 添加错误处理日志
# 获取最新的帖子ID
if posts:
new_post_id = posts[0].find("a")["href"].split("/")[-1]
print(f"最新帖子ID: {new_post_id}") # 添加日志
# 如果有新帖子
if latest_post_id is None:
latest_post_id = new_post_id
print("发现首个帖子,设置最新帖子ID。") # 添加日志
elif new_post_id != latest_post_id:
latest_post_id = new_post_id
print("发现新帖子!") # 添加日志
notify_new_post(posts[0])
def notify_new_post(post):
title = post.find("a").text
link = post.find("a")["href"]
full_link = f"https://bbs.z-xin.net{link}" if link.startswith("/") else link
# 这里可以使用任何推送服务,如邮件、微信、钉钉等,下面是一个简单的打印替代推送
print(f"新帖子:{title}\n链接:{full_link}\n时间:{datetime.now()}\n")
# 每隔5秒检查一次,可根据实际需求调整检查频率
schedule.every(5).seconds.do(check_forum)
while True:
schedule.run_pending()
time.sleep(1)