代码概述:通过去指定的天气网站抓取本地当天信息,并且提取相关字段从而来判断是否要去带伞,并且发送邮件给指定用户;
import json from urllib import request from urllib.request import urlopen import smtplib from email.mime.text import MIMEText from emilconf import * def readUrl(url): # 生成字典, 指定用户代理为火狐浏览器, 而不是python脚本; headers = {'User-Agent': 'Firefox/23.0'} # 向url地址发起请求, 返回一个Request对象; req = request.Request(url, headers=headers) # 返回一个urlOpen对象, 该对象中包含访问的所有结果, 比如: 网页内容, 网页的状态码(200, 404) urlObj = urlopen(req) # 将读取的内容以utf-8编码显示;(中文显示不乱码) urlContent = urlObj.read().decode('utf-8') return urlContent def sendMail(): def mail(): msg = MIMEText(content, 'plain', 'utf8') msg['From'] = sender msg['To'] = receiver msg['Subject'] = subject return msg def sendmail(): try: smt = smtplib.SMTP('smtp.163.com') smt.login(sender, passwd) msg = mail() smt.sendmail(sender, receiver, msg.as_string()) except smtplib.SMTPException as e: print('发送失败:', e) else: print('发送成功!') return sendmail() # def main(): url = "http://www.weather.com.cn/data/cityinfo/101110101.html" info = readUrl(url) d = json.loads(info) weather = d['weatherinfo']['weather'] if '雨' in weather or '阴' in weather: sendMail() main()