1. 程式人生 > >python獲取天氣+email通知

python獲取天氣+email通知

python

信息抓取來源:http://www.tianqi.com/(天氣網

郵件服務器(發送):126郵箱

郵件服務器(接收):QQ郵箱


代碼如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*- 

import smtplib
import urllib,urllib2
import re

#定義函數,發送郵件
def sendMail(body):
    smtp_server = 'smtp.126.com'
    from_mail = '[email protected]'
    
    #密碼使用授權碼替代,否則會報535等認證錯誤
    mail_pass = '*********'
    to_mail = ['[email protected]']
    from_name = 'Weather Monitor'
    subject = 'Raining Today!'
    mail = [
        "From: %s <%s>" % (from_name, from_mail),
        "To: %s" % ','.join(to_mail),
        "Subject: %s" % subject,
        "",
        body
        ]
    msg = '\n'.join(mail)
    try:
        s = smtplib.SMTP_SSL('smtp.126.com',465)
        s.login(from_mail, mail_pass)
        s.sendmail(from_mail, to_mail, msg)
        s.quit()
    except smtplib.SMTPException as e:
        raise e
        
if __name__ == "__main__":
    headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
    
    #定位城市,深圳
    url='http://www.tianqi.com/shenzhen/'
    try:
        request = urllib2.Request(url,headers=headers)
        response = urllib2.urlopen(request)
        urlhtml = response.read()
    
    except Exception as e:
        raise e
    
    #抓取關鍵字正則表達式    
    re_page = re.compile(r'<dd class="name">.*?<h2>(.*?)</h2>.*?<dd class="week">(.*?)</dd>.*?<span>.*?<b>(.*?)</b>(.*?)</span>',re.S)
    
    items = re_page.findall(urlhtml)
    dic = {}
    dic["城市"] = items[0][0]
    dic["日期"] = items[0][1]
    dic["天氣"] = items[0][2]
    dic["溫度"] = items[0][3]
    
    #判斷天氣是否含有“雨”關鍵字
    if "雨" in dic["天氣"]:
        sendMail("It's rainy today. Remember to bring your umbrella!" +"\n" +"城市: " +dic["城市"] +"\n" +"日期: " +dic["日期"] +"\n" +"天氣: " +dic["天氣"] +"\n" +"溫度: " +dic["溫度"])


運行結果:

技術分享圖片



python獲取天氣+email通知