【Python】用Python获取天气并定时自动发送到邮箱

以前用Python写的一个定时获取天气情况,并用邮件发送的小功能,需要使用到一点网页数据解析.

获取天气,发送邮件的函数:

刚刚测试了下,这个网站可能已经停更了.最新更新还是五月二十八,但是思路是这样,没问题.

# coding: utf-8
import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import urllib2
import json
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import time
cityname = "天津"
citycode = '101030100'

if __name__ == '__main__':
    time.sleep(10)
    if citycode:
        try:
            url = "http://tj.nineton.cn/Heart/index/all?city=CHTJ000000&language=zh-chs&unit=c&aqi=city&alarm=1&key=78928e706123c1a8f1766f062bc8676b"  # 构造网址
            content = urllib2.urlopen(url).read() # 读取网页源代码
            content = content.decode("utf-8").encode("utf-8")
            data = json.loads(content)  # 使用json库将字符转化为字典
             # 使用json库将字符转化为字典
            zero = data['weather'][0]["now"]["text"]
            one=data['weather'][0]["today"]["suggestion"]["dressing"]["details"]
            two=data['weather'][0]["today"]["suggestion"]["flu"]["details"]
            four=data['weather'][0]["now"]["temperature"]
            five=data['weather'][0]["now"]["feels_like"]
            six=data['weather'][0]["now"]["air_quality"]["city"]["quality"]
            severn=data['weather'][0]["last_update"]
              # 获取字典
             # 格式化字符
              # 输出天气信息
        except Exception:
            print("Not Found!!")
    now = datetime.datetime.now()
    c=now.strftime('%Y-%m-%d %H:%M:%S')  # 时间转换
    en = '%s天气'%c
    try:
        sender = '[email protected]'   # 邮件发送者
        receiver = '[email protected]'  # 邮件接收者,个人用''就可以
        # receiver = ['[email protected]',[email protected]] # 多个接收者的时候
        subject = en
        smtpserver = 'smtp.163.com'
        username = '[email protected]'   # 使用的邮箱服务器用户
        password = 'password'      # 密码

        neirong = '今日天津的天气预报:''\n' \
                  '天气:%s''\n' \
                  '穿衣建议:%s''\n' \
                  '注意提示:%s''\n' \
                  '当前温度:%s''\n' \
                  '体感:%s''\n' \
                  '空气质量:%s''\n' \
                  '最后一次更新时间:%s''\n' % (zero,
                                        one,
                                        two,
                                        four,
                                        five,
                                        six,
                                        severn)
        msg = MIMEText(neirong, 'plain', 'utf-8')  # 中文需参数‘utf-8',单字节字符不需要
        msg['Subject'] = Header(subject, 'utf-8')
        msg['From'] = 'Yu<[email protected]>'   # 发送者的邮箱
        smtp = smtplib.SMTP()
        smtp.connect('smtp.163.com')   # 服务器地址
        smtp.login(username, password)  # 登录服务器
        smtp.sendmail(sender, receiver, msg.as_string())
        smtp.quit()
        print "success"
    except Exception,e:
        print e
        print "failed"

## xxx换成自己的邮箱,密码

定时任务的实现:

使用到Linux中的crontab.
在终端输入:

crontab -e

如果想每天7:00获取可以,输入:

0 7 * * * python /pwd/tianqi.py
## pwd表示py文件的绝对路径

每隔五分钟的实现:

*/5 * * * * python /pwd/tianqi.py
## pwd表示py文件的绝对路径
# */5表示每五分钟

猜你喜欢

转载自blog.csdn.net/lvluobo/article/details/80954433