环境:vps,centos7,python3.8.10,青龙面板(用宝塔安装)
任务:用python代码,监控一个网站页面是否有更新(新帖子),若有,则提醒(发布到wordpress或者发送到微信)。
备注:本程序检测更新情况,没有用到数据库。而是采用列表对比的方法,即上次的情况存到列表pre_list中,一分钟后,将本次的情况存到列表now_list中,然后对比两个列表,如果now_list中有,但pre_list无,即表示有了新帖子。
所以,在检测程序A.py中,使用了while无限循环。
在实际运行中,出现了一个问题,就是长时间运行后,程序会报错[Errno 101] Network unreachable'),我猜测是长时间高频率访问网站,被网站强制断网了(但还不是反爬非常严重,过一会再运行就又能成功了)。
于是,我设计这样一个思路。
编写一个程序B.py,使用青龙半小时运行一次B.py,B.py的作用是用于查看程序A.py是否处于运行中,如果A.py在运行,就什么都不做,如果A.py终止了,则启动A.py。
下面分别来实现A.py和B.py。
#A.py,循环检测网页是否有更新(新帖子)
import requests
from bs4 import BeautifulSoup
import time
from lxml import etree
#from wordpress_xmlrpc import Client, WordPressPost
#from wordpress_xmlrpc.methods.posts import NewPost
import datetime
import json
def pushplus_notify(title,content):
print('将消息发送至WX')#略
def Get_Content(url):
print('得到新帖子的内容')#略
proxies = {'http': "socks5://127.0.0.1:10808",'https': "socks5://127.0.0.1:10808"}
headers={
#略
}
pre_list=[]
url='https://xxx.com'
r=requests.get(url,headers=headers,proxies=proxies)
bs = BeautifulSoup(r.text, 'html.parser')
id_nodes=bs.find_all('a',attrs={"class":'xxx'})
for id_node in id_nodes:
pre_list.append(id_node.get('href'))#初始化pre_list
prev_time = time.time()
while True:
curr_time = time.time()
if curr_time - prev_time >= 60:
url='https://xxx.com'
r=requests.get(url,headers=headers,proxies=proxies)
bs = BeautifulSoup(r.text, 'html.parser')
id_nodes=bs.find_all('a',attrs={"class":'xxx'})
now_list=[]
for id_node in id_nodes:
now_list.append(id_node.get('href'))
new_elements=[x for x in now_list if x not in pre_list]#now_list(一般用于存放本次新数据)中有、但pre_list(一般用于存放上次数据<旧数据>)中没有的元素
if len(new_elements)>0:
print('有新贴了,'+str(new_elements))
pre_list=now_list
prev_time = curr_time
#获取新帖内容(为了演示方便,我只取新帖子们的第一个帖子[因为有可能有多个新帖])
good_content=Get_Content(new_elements[0])
good_content=good_content.replace('\\','')
now = datetime.datetime.now()
title = now.strftime("%Y-%m-%d_%H-%M-%S")
pushplus_notify(title,good_content)
time.sleep(2)
time.sleep(2)
下面是使用青龙每半小时运行、检测A.py程序是否还在正常运行的B.py。
import psutil
import subprocess
def check_process(process_name):
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
if proc.info['name'] == 'python3' and len(proc.info['cmdline']) > 1 and proc.info['cmdline'][1] == process_name:
return True
return False
def start_process(script_path):
subprocess.Popen(['python3', script_path])
# 指定要检测的脚本名
script_name = "A.py" # 替换为实际脚本名称
script_path = "A.py" # 替换为实际脚本路径
# 检测进程是否在运行
if check_process(script_name):
print(f"进程 {script_name} 正在运行.")
else:
print(f"进程 {script_name} 没有在运行,正在启动...")
start_process(script_path)
print(f"进程 {script_name} 已启动.")
说明:
(1)可以使用ps -ef | grep python3观察A.py是否正在运行
参考我的文章:
记录centos中操作(查找、结束、批量)进程以及crontab定时写法的知识-CSDN博客
(2)每个半小时运行的crontab写法
(3)不要忘记在青龙的“依赖管理”中添加相应的库
(4)通过青龙将A.py和B.py放入VPS中,无需使用FileZilla Client。