1. 程式人生 > >利用python監控天氣

利用python監控天氣

圖片 ping name rom font strong == 分享圖片 agen

需求:

從天氣網站抓取天氣,在每天6點,檢查當天是否會下雨。如果下雨,郵件提醒帶傘。


代碼:

[root@pos ~]# cat weather.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests,bs4,smtplib
def sendMail(body):
    smtp_server = 'smtp.126.com'
    from_mail = '[email protected]'
    mail_pass = 'xxxxxxxxxx'
    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:
        print("Error: "+e)
if __name__ == "__main__":
    headers={'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0'}
    url='http://www.tianqi.com/shanghai/'
    urlhtml=requests.get(url,headers=headers)
    urlhtml.raise_for_status()
    weatherhtml=bs4.BeautifulSoup(urlhtml.text[:],'html.parser')
    weather=weatherhtml.select('div li b')
    for i in range(len(weather)):
        weathnow=weather[i].getText()
        if weathnow == '帶傘':
            sendMail("It's rainy today. Remember to bring your umbrella!")
            print("DONE!")

將腳本寫入計劃任務,每天6點執行一次。

計劃任務可以采用Task Scheduler(windows)、launchd(OS X)、cron(linux)等系統工具。


效果:

技術分享圖片


當然,也可以采用發送短信的方式進行通知。


利用python監控天氣