|
| 1 | +#!/usr/bin/python |
| 2 | +# coding=utf-8 |
| 3 | + |
| 4 | +import sys |
| 5 | + |
| 6 | +reload(sys) |
| 7 | +sys.setdefaultencoding('utf8') |
| 8 | + |
| 9 | + |
| 10 | +from bs4 import BeautifulSoup |
| 11 | +import urllib2 |
| 12 | +def fetch_weather_datas(): |
| 13 | + # 请求页面数据 |
| 14 | + response = urllib2.urlopen(url='http://www.weather.com.cn/weather/101010100.shtml') |
| 15 | + body = response.read() |
| 16 | + |
| 17 | + # 用BeautifulSoup解析,取出7天的天气数据 |
| 18 | + soup = BeautifulSoup(body) |
| 19 | + tags = soup.select('#7d > ul > li') |
| 20 | + |
| 21 | + return ['%s\t%s\t%s\t%s' % # 对七天的数据分别解析,将解析后的每天的数据拼接成“日期+天气+最高气温+最低气温”的字符串,\t分隔 |
| 22 | + ( |
| 23 | + tag.select('h1')[0].string, # 取时间数据 |
| 24 | + tag.select('.wea')[0]['title'], # 取天气数据 |
| 25 | + tag.select('.tem > span')[0].string, # 取最高气温 |
| 26 | + tag.select('.tem > i')[0].string # 取最低气温 |
| 27 | + ) |
| 28 | + for tag in tags] # 返回结果为List |
| 29 | + |
| 30 | +# 发送邮件 |
| 31 | +import smtplib |
| 32 | +from email.mime.text import MIMEText |
| 33 | +from email.header import Header |
| 34 | +def send_mail(receivers, text): |
| 35 | + # 第三方 SMTP 服务 |
| 36 | + mail_host = 'smtp.sina.com' # 设置服务器 |
| 37 | + mail_user = '[email protected]' # 用户名 |
| 38 | + mail_pass = 'qwer&1234.' # 口令 |
| 39 | + |
| 40 | + message = MIMEText(text, 'plain', 'utf-8') |
| 41 | + message['From'] = Header(mail_user) |
| 42 | + message['To'] = Header(','.join(receivers), 'utf-8') |
| 43 | + message['Subject'] = Header('天气提醒', 'utf-8') |
| 44 | + |
| 45 | + try: |
| 46 | + smtpObj = smtplib.SMTP() |
| 47 | + smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 |
| 48 | + log('连接服务器成功..') |
| 49 | + smtpObj.login(mail_user, mail_pass) |
| 50 | + log('登录邮箱服务器成功..') |
| 51 | + smtpObj.sendmail(from_addr=mail_user, to_addrs=receivers, msg=message.as_string()) |
| 52 | + log('邮件发送成功..') |
| 53 | + except smtplib.SMTPException as e: |
| 54 | + log('无法发送邮件...' + e.message) |
| 55 | + |
| 56 | + |
| 57 | +# 传入爬到的天气数据 |
| 58 | +def is_need_remind(weather_datas): |
| 59 | + return '雨' in weather_datas[0] |
| 60 | + |
| 61 | +# 从配置文件中,读取接收方邮箱地址List |
| 62 | +def read_receivers(path): |
| 63 | + return [line.strip('\t') for line in open(path, 'r').readlines()] |
| 64 | + |
| 65 | + |
| 66 | +# 日志打印 |
| 67 | +import time |
| 68 | +def log(msg): |
| 69 | + timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) |
| 70 | + print '[%s] %s' % (timestamp, msg) |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | +# 主函数 |
| 75 | +def main(): |
| 76 | + try: |
| 77 | + weather_datas = fetch_weather_datas() |
| 78 | + if is_need_remind(weather_datas): |
| 79 | + send_mail(read_receivers('receivers.txt'), '\n'.join(weather_datas)) |
| 80 | + else: |
| 81 | + log('今天天气良好') |
| 82 | + except Exception, e: |
| 83 | + log('出错..') |
| 84 | + send_mail([ '[email protected]'], '天气提醒Job出现异常...') |
| 85 | + |
| 86 | + |
| 87 | +# 执行主函数 |
| 88 | +main() |
| 89 | + |
0 commit comments