xinghe0 发表于 2018-8-13 08:51:31

利用python监控天气

# cat weather.py  
#!/usr/bin/python
  
# -*- coding: UTF-8 -*-
  
import requests,bs4,smtplib
  
def sendMail(body):
  
    smtp_server = 'smtp.126.com'
  
    from_mail = 'pp_1990@126.com'
  
    mail_pass = 'xxxxxxxxxx'
  
    to_mail = ['50xxxxxx6@qq.com']
  
    from_name = 'Weather Monitor'
  
    subject = 'Raining Today!'
  
    mail = [
  
      &quot;From: %s <%s>&quot; % (from_name, from_mail),
  
      &quot;To: %s&quot; % ','.join(to_mail),
  
      &quot;Subject: %s&quot; % subject,
  
      &quot;&quot;,
  
      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(&quot;Error: &quot;+e)
  
if __name__ == &quot;__main__&quot;:
  
    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 p')
  
    for i in range(len(weather)):
  
      weathnow=weather.getText()
  
      if weathnow == '有雨':
  
            sendMail(&quot;It's rainy today. Remember to bring your umbrella!&quot;)
  
            print(&quot;DONE!&quot;)
页: [1]
查看完整版本: 利用python监控天气