Python 爬取网站最新文章并短信+邮件提醒
iamdu2020-01-03 15:58:44Python 浏览: 184317 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
from twilio.rest import Client
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 duanxin():
account_sid = "AC90df5c4a788a941a148e64c1138bde69"
auth_token = "95df459c5c66a678aaaf9d35610aaa86"
client = Client(account_sid, auth_token)
message = client.messages.create(
to="+8613610091039",
from_="+18125589182",
body="大拿DU又更新博客了:"+ laste_title[0:30])
def job():
blog()
otxt()
duanxin()
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 条评论