利用python爬虫和企业微信进行监控和通知

Posted by ZMY on July 2, 2021

利用python爬虫和企业微信进行监控和通知

项目背景

朋友最近好像在炒币,问我有没有办法能够及时的获取一个网站的更新信息,即这个网站有一个功能占时是关闭的,这个功能不确定在某一个时间会打开,朋友想第一时间收到这个功能打开的消息。查看了一下这个网站,最后决定用python爬虫+企业微信api来写个脚本监控这个网站的状态更新情况,并在第一时间通过微信通知对方。

一.python爬虫

python爬虫准备用selenium+bs4+requests方式处理

1.安装python模块

# pip3 install requests beautifulsoup4 selenium

2.安装chrome和下载对应版本的chromedriver

2.1 创建yum文件

# cd /etc/yum.repos.d/
# touch google-chrome.repo

2.2 输入yum源信息

[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub

2.3 安装google chrome

# yum -y install google-chrome-stable --nogpgcheck

2.4 查看chrome版本信息,我这里是91.0.4472.114

[root@master shibatoken]# google-chrome-stable --version
Google Chrome 91.0.4472.114 

2.5 下载对应版本的chromedriver驱动,解压并赋值权限

下载地址http://npm.taobao.org/mirrors/chromedriver/

# wget http://npm.taobao.org/mirrors/chromedriver/91.0.4472.101/chromedriver_linux64.zip 
# unzip chromedriver_linux64.zip
# chmod 777 chromedriver

3.查看网页信息

先看一下需要检查的网页功能模块的状态,如下图所示,这个现在为灰色的模块即为要监测的模块,要在他变成可用状态的时候观测到,需要先看一下这个元素对应的html代码

对应代码如下

可以看到元素a的class中有inactive表示未激活状态,那么大概率这个功能上线的时候不会出现inactive在class中,因此思路就是python爬虫抓取这个模块下的inactive关键字,当没有inactive关键字时,功能模块处于上线状态

二.python企业微信api

企业微信需要先注册一下,需要的信息有企业id,secret,agentid,用户名

如何获取这4个信息,请看具体注册流程请看之前写的zabbix监控中关于企业微信绑定的信息blog地址

我这里还是利用zabbix监控中申请的zabbix应用

三.python脚本代码

python版本3.6+,代码如下直接运行即可

import requests
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
import time
import json



class WeChat:
    def __init__(self):
        self.CORPID = 'wwd81528c74890f6c3'  #企业ID,在管理后台获取
        self.CORPSECRET = 'PI1yNaklf-f9LwfQfQVDkWCqSWJ7HWdLL7g1U64Qa1I'#自建应用的Secret,每个自建应用里都有单独的secret
        self.AGENTID = '1000002'  #应用ID,在后台应用中获取
        self.TOUSER = "ZhaiMingYu"  # 接收者用户名,多个用户用|分割

    def _get_access_token(self):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
        values = {'corpid': self.CORPID,
                  'corpsecret': self.CORPSECRET,
                  }
        req = requests.post(url, params=values)
        data = json.loads(req.text)
        return data["access_token"]

    def get_access_token(self):
        try:
            with open('access_token.conf', 'r') as f:
                t, access_token = f.read().split()
        except:
            with open('access_token.conf', 'w') as f:
                access_token = self._get_access_token()
                cur_time = time.time()
                f.write('\t'.join([str(cur_time), access_token]))
                return access_token
        else:
            cur_time = time.time()
            if 0 < cur_time - float(t) < 7260:
                return access_token
            else:
                with open('access_token.conf', 'w') as f:
                    access_token = self._get_access_token()
                    f.write('\t'.join([str(cur_time), access_token]))
                    return access_token

    def send_data(self, message):
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": self.TOUSER,
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
                "content": message
                },
            "safe": "0"
            }
        send_msges=(bytes(json.dumps(send_values), 'utf-8'))
        respone = requests.post(send_url, send_msges)
        respone = respone.json()   #当返回的数据是json串的时候直接用.json即可将respone转换成字典
        return respone["errmsg"]




def wx_send():
    wx = WeChat()
    wx.send_data("ShibaSwap is online")
    wx.send_data("ShibaSwap is online")


def if_online():    
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    driver = webdriver.Chrome('./chromedriver',chrome_options=chrome_options)
    html=driver.get("https://shibatoken.com/index.html")
    content = driver.page_source.encode('utf-8')
    soup = BeautifulSoup(content,'html.parser')
    s= soup.find_all('div',text='Use ShibaSwap')[0].parent['class']
    driver.close()
    print(s)
    return s


online = 'False'


while online == 'False':
    if "inactive" not in if_online():
        print("ShibaSwap is online")
        wx_send()
        online = 'True'
    time.sleep(10)

四.验证信息

当网站对应功能的html代码中的inactive更改之后,微信可收到信息

声明:本博客的原创文章,都是本人平时学习所做的笔记,转载请标注出处,谢谢合作。