公司要求给爬虫项目添加监控,要求可以检测每天爬虫是否存活和数据流量,我的想法是直接监控爬虫并且通过机器人发送到企业微信的群里
构建消息封装类
class WX_CONTENT():
def __init__(self, content, spider, kind, title):
self.content = content
self.spider = spider
self.kind = kind
self.title = title
def add_element(self, title, content):
result = '>{}:<font color=\"comment\">{}</font>\n'.format(title, content)
return result
def get_Msg(self):
content = "爬虫项目消息通知<font color=\"warning\">{}</font>,请相关同事注意。\n".format(self.title)
if self.spider:
msg = self.add_element(title='Spider Name', content=self.spider)
content += msg
if self.content:
msg = self.add_element(title='Message', content=self.content)
content += msg
if self.kind:
msg = self.add_element(title='Log Level', content=self.kind)
content += msg
return content
cc = WX_CONTENT(content='采集完毕', spider='拟建项目', kind='info', title='消息通知')
content = cc.get_Msg()
消息发送
import requests
def send_weixin(content):
url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=你的机器人的key" # 这里就是群机器人的Webhook地址
headers = {"Content-Type": "application/json"} # http数据头,类型为json
data = {
"msgtype": "markdown",
"markdown": {
"content": content,
"mentioned_list": ["@all", ], # @全体成员
}
}
r = requests.post(url, headers=headers, json=data) # 利用requests库发送post请求
send_weixin(content)
结果图
怎么添加并且查看机器人的key
群里当中选择添加一个机器人
给机器人起一个名字,比如给r数来一刀
最后就添加成功了 并且可以看到webhook
后记
之后会写一个关于scrapy项目的监控扩展 并且每天发送消息到企业微信群当中,如果有需求的就点一个关注吧