微信咨询

微信咨询

13610*910*9

服务热线 7*24小时

电话咨询

Python 抓取网站最新文章并且发送到邮箱提醒

iamdu2020-01-01 12:50:28 浏览: 291437
import requests
import smtplib
import schedule
import time
from bs4 import BeautifulSoup
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header

account = '121942198@qq.com'
password = ''#QQ授权码
receiver = '76123708@qq.com'

#发送邮件
def send_email():
    mailhost='smtp.qq.com'
    qqmail = smtplib.SMTP_SSL(host='smtp.qq.com')
    qqmail.connect(mailhost,465)
    qqmail.login(account,password)

    # 以html格式构建邮件内容
    send_str = '''
    <html>
    <body>
    <center>你关注的作者更新了博客,标题是:'''+ laste_title +'''</center>
    </body>
    </html>
    '''

    # 构建message
    message = MIMEMultipart()
    # 添加邮件内容
    content = MIMEText(send_str, _subtype='html', _charset='utf8')
    message.attach(content)


    #定义邮件头信息
    # message['From'] = Header(u'SuperME <%s>'%account)
    h = Header('打伞小和尚', 'utf-8') #有中文得分2段处理
    h.append('<%s>'%account, 'ascii')
    message["From"] = h
    message['to'] = Header(u'DU <%s>'%receiver)
    message['Subject'] = Header('博客更新了', 'utf-8')
    try:
        qqmail.sendmail(account, receiver, message.as_string())
        print ('邮件发送成功')
    except:
        print ('邮件发送失败')
    qqmail.quit()
#抓取最新博客文章标题
def blog():
    res =requests.get('http://www.iamdu.com')
    html=res.text
    soup = BeautifulSoup( html,'html.parser')
    global laste_title
    laste_title = soup.find(class_='content-area').find(class_='entry-title').text  

#打开文档,存储有之前最新的博客标题
def otxt():
    with open('article.txt', 'r', encoding='utf-8') as f:
        global txt_title
        txt_title = f.read()

# 打印欢迎信息
def print_info():
    print('*'*20 + 'Welcome' + '*'*20)
    print('[Function]: 博客更新邮件提示系统')
    print('[Author]: DU')
    print('[Mail]: i@iamdu.com')
    print('*'*21 + 'Start' + '*'*21)

def job():

    blog()
    otxt()
    if laste_title != txt_title:
        #写入最新的标题
        with open('article.txt', 'w', encoding='utf-8') as f:
            f.write(laste_title)

        print('开始一次任务')
        send_email()
        print('任务完成')

print_info()
schedule.every(1).minutes.do(job)
while True:
    schedule.run_pending()
    time.sleep(1)

 

欢迎留下你的看法

共 0 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注