python擷取天氣+email通知

來源:互聯網
上載者:User

標籤:python

資訊抓取來源:http://www.tianqi.com/(天氣網 )

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

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


代碼如下:

#!/usr/bin/env python# -*- coding:utf-8 -*- import smtplibimport urllib,urllib2import 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        #抓取關鍵字Regex        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通知

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.