luoson1 发表于 2018-8-3 10:51:45

python获取天气+email通知

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

  
import smtplib
  
import urllib,urllib2
  
import re
  

  
#定义函数,发送邮件
  
def sendMail(body):
  
    smtp_server = 'smtp.126.com'
  
    from_mail = 'hzpzc68@126.com'
  

  
    #密码使用授权码替代,否则会报535等认证错误
  
    mail_pass = '*********'
  
    to_mail = ['1124657106@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:
  
      raise e
  

  
if __name__ == &quot;__main__&quot;:
  
    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=&quot;name&quot;>.*?<h2>(.*?)</h2>.*?<dd class=&quot;week&quot;>(.*?)</dd>.*?<span>.*?<b>(.*?)</b>(.*?)</span>',re.S)
  

  
    items = re_page.findall(urlhtml)
  
    dic = {}
  
    dic[&quot;城市&quot;] = items
  
    dic[&quot;日期&quot;] = items
  
    dic[&quot;天气&quot;] = items
  
    dic[&quot;温度&quot;] = items
  

  
    #判断天气是否含有“雨”关键字
  
    if &quot;雨&quot; in dic[&quot;天气&quot;]:
  
      sendMail(&quot;It's rainy today. Remember to bring your umbrella!&quot; +&quot;\n&quot; +&quot;城市: &quot; +dic[&quot;城市&quot;] +&quot;\n&quot; +&quot;日期: &quot; +dic[&quot;日期&quot;] +&quot;\n&quot; +&quot;天气: &quot; +dic[&quot;天气&quot;] +&quot;\n&quot; +&quot;温度: &quot; +dic[&quot;温度&quot;])
页: [1]
查看完整版本: python获取天气+email通知