简单的监听脚本

不断刷新获取某个网址页面的数据,监听页面是否包含所需要的信息,发现内容后发邮件通知。

__author__ = 'Administrator'
# coding:utf-8
import urllib.request

from tkinter import *
import time
import random
import smtplib
from email.mime.text import MIMEText
from email.header import Header


def send(msg):
    mail_user = "xxxxxxxx"  # 发送邮箱的 用户名
    mail_pass = "xxxxxxxx"  # 发送邮箱的 口令
    sender = '[email protected]'  # 发送邮箱
    to = '[email protected]'  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
    mail_host = "smtp.126.com"

    receivers = [to]
    message = MIMEText(msg, 'plain', 'utf-8')
    message['From'] = sender
    message['To'] = to
    subject = '系统检测通知'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print
        "邮件发送成功"
    except Exception as e:
        print
        "Error: 无法发送邮件"
        print(e)


dd = set()


def get():
    global dd
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
    url = 'https://bbs.meizu.cn/forum.php?mod=forumdisplay&fid=22&orderby=dateline'
    req = urllib.request.Request(url=url, headers=headers)
    pattern = re.compile(r'>(.*m码.*)<', re.IGNORECASE)
    htmlcode = urllib.request.urlopen(req).read().decode('utf-8')  # 读取页面源码
    r = pattern.findall(htmlcode)
    print('catching...')
    t = set(r) - dd
    if len(t) > 0:
        dd = dd | t
        msg = ''.join(t)
        print(msg)
        send(msg)


while True:
    get()
    time.sleep(random.randint(60, 120))

你可能感兴趣的:(简单的监听脚本)