使用 Python 爬取研究生官网最新公告通知并推送微信消息

效果

原理很简单,我只需要使用BeautifulSoup库每隔一段时间爬取一下官网网页的内容,然后把通知有关的信息存入一个数据库判断是不是新的通知就可以。如果是新的通知就使用虾推啥推送微信消息。效果如下:

为了代码一直运行,所以我将它直接扔到服务器。让它一直跑着就行了。

代码

这里需要用到虾推啥,一行代码推送手机通知。
虾推啥官网教程链接

整体代码都比较简单易懂,小白也可以使用。
Python代码:

python 复制代码
import pymysql
import requests
from bs4 import BeautifulSoup
import time
# 数据库信息自己填写
db_config = {
    'host': '***',
    'user': '**',
    'passwd': '***',
    'port': 3306,
    'db': '***',
    'charset': 'utf8'
}
db = pymysql.connect(**db_config)


def get_html(url):
    r = requests.get(url)
    r.encoding = "utf-8"
    if r.status_code != 200:
        raise Exception()
    return r.text


def parse_html(html_doc, element, class_name):
    soup = BeautifulSoup(html_doc, "html.parser")
    dev_nodes = soup.find_all(element, class_=class_name)
    return dev_nodes


def insert_into_db(title, url, date):
    cursor = db.cursor()
    sql = "SELECT * FROM notice WHERE title = %s"
    cursor.execute(sql, (title,))
    if not cursor.fetchone():
        sql = "INSERT INTO notice(title, content, date) VALUES (%s, %s, %s)"
        try:
            cursor.execute(sql, (title, url, date))
            db.commit()
        except:
            db.rollback()
            print("插入失败")


def is_new(title):
    cursor = db.cursor()
    sql = "SELECT * FROM notice WHERE title = %s"
    cursor.execute(sql, (title,))
    if not cursor.fetchone():
        return True
    return False


def send_message(title, url, date, stitute):
    mydata = {
        'text': stitute,
        'desp': '内容:' + title + '<br>' \
                                  '网址:' + '<a href="' + url + '">' + url + '</a>' + '<br>' \
                                                                                      '日期:' + date
    }
    requests.post('https://wx.xtuis.cn/您的token.send', data=mydata)
    # 注意这里要换成你自己的token

def CIE():
    url = "https://*****" # 这里要根据自己学校的官网填写,并且网页布局也不一样,获取元素逻辑不一样
    bs_url = "https://****"
    html_doc = get_html(url)
    dev_nodes = parse_html(html_doc, "li", "first")
    title = dev_nodes[0].find("a").get_text().strip()
    date = dev_nodes[0].find("span").get_text()
    to_url = bs_url + dev_nodes[0].find("a")["href"]
    # 上面几行都是获取页面元素的逻辑,要根据实际情况修改。
    if is_new(title):
        print("信息工程学院官网有新公告!")
        insert_into_db(title, to_url, date)
        send_message(title, to_url, date, "信息工程学院官网有新公告!")
    else:
        print("无新公告!")


def GraduateSchool():
    url = "https://****" # 同上
    bs_url = "https://***"
    html_doc = get_html(url)
    dev_nodes = parse_html(html_doc, "a", "tit")
    title = dev_nodes[0].get_text()
    content = bs_url + dev_nodes[0]['href']
    date = parse_html(html_doc, 'li', "first")[0].get_text()
    if is_new(title):
        print("研究生学院官网有新公告!!")
        insert_into_db(title, content, date)
        send_message(title, content, date, "研究生学院官网有新公告!")
    else:
        print("无新公告!")


while True:
    CIE()
    GraduateSchool()
    print("目前时间:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    time.sleep(60 * 5)

注意根据自己的实际情况修改代码中自己的参数。

相关推荐
A__tao23 分钟前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
研究点啥好呢27 分钟前
Github热门项目推荐 | 创建你的像素风格!
c++·python·node.js·github·开源软件
lly20240638 分钟前
C 标准库 - `<stdio.h>`
开发语言
沫璃染墨40 分钟前
C++ string 从入门到精通:构造、迭代器、容量接口全解析
c语言·开发语言·c++
jwn99940 分钟前
Laravel6.x核心特性全解析
开发语言·php·laravel
迷藏49442 分钟前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
功德+n1 小时前
Linux下安装与配置Docker完整详细步骤
linux·运维·服务器·开发语言·docker·centos
明日清晨1 小时前
python扫码登录dy
开发语言·python
我是唐青枫1 小时前
C#.NET gRPC 深入解析:Proto 定义、流式调用与服务间通信取舍
开发语言·c#·.net
JJay.1 小时前
Kotlin 高阶函数学习指南
android·开发语言·kotlin