python获取天气状况并以邮件的形式发到目的邮箱

python爬取天气情况

下面为示例代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.error import HTTPError
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import time

"""爬虫程序是一个需要后期投入很大维护力度的,就比如网页开发者将来在某一时间重构了html代码,这就很有可能导致爬虫程序的失败,所以写爬虫程序要尽量做到未雨绸缪,让爬虫程序更健壮,这样你才能睡一个安稳的觉这个程序很简单,大体分为两个部分,爬虫部分和邮件部分,代码还有很大的优化空间,比如一些常量可以拿到外面,这样代码看起来会更整洁,邮件内容是以html格式的形式发送的,这样你就可以改成自己喜欢的样式。我不建议你频繁的去发邮件,邮箱可能会被封掉,信件退回,导致发送失败发送电子邮件的邮箱要开启smtp客户端功能,邮箱——>设置——>开启SMTP服务,获取授权码(就是程序里需要登陆邮箱的密码)"""#获取当天的天气情况
def get_weather(url):
    try:
        html=urlopen(url).read()
    except HTTPError as e:
        return None
    try:
        weather_list=[]
        bs0bj=BeautifulSoup(html,"html.parser")
        time.sleep(5)
        weather=bs0bj.find("div",{"class":"condition-icon wx-weather-icon vector"}).next_siblings
        title=bs0bj.body.h1.get_text()
        weather_list.append(title)
        for next in weather:
            weather_list.append(next.get_text())
    except AttributeError as e:
        return None
    return weather_list
#获取未来5天的天气情况
def get_5weathers(url):
    try:
        html=urlopen(url).read()
    except HTTPError as e:
        return None
    try:
        weather5_list=[]
        bs0bj=BeautifulSoup(html,"html.parser")
        weathers=bs0bj.find("table",{"class":"twc-table"}).tbody
        for child in weathers.children:
            list1=[]
            for i in child.children:
                list1.append(i.get_text())
            list1.remove("")
            weather5_list.append(list1)
    except AttributeError as e:
        return None
    return weather5_list
#等到的数据形如一下数据格式
# weather=[‘北京, 中国‘, ‘3°‘, ‘晴朗‘, ‘体感温度 -1°‘, ‘高温 -- 低温 -7°紫外线指数 0(最大值10)‘]
# weathers=[[‘今天晚上\n12月 18日‘, ‘大部晴朗‘, ‘---7°‘, ‘0%‘, ‘北 15 公里 /小时 ‘, ‘40%‘], [‘星期二12月 19日‘, ‘晴朗‘, ‘5°-5°‘, ‘0%‘, ‘西南 21 公里 /小时 ‘, ‘32%‘], [‘星期三12月 20日‘, ‘晴朗‘, ‘7°-6°‘, ‘0%‘, ‘西北 22 公里 /小时 ‘, ‘33%‘], [‘星期四12月 21日‘, ‘晴朗‘, ‘6°-6°‘, ‘0%‘, ‘西南西 11 公里 /小时 ‘, ‘41%‘], [‘星期五12月 22日‘, ‘晴朗‘, ‘8°-6°‘, ‘0%‘, ‘北 16 公里 /小时 ‘, ‘30%‘], [‘星期六12月 23日‘, ‘晴朗‘, ‘8°-3°‘, ‘0%‘, ‘西北西 14 公里 /小时 ‘, ‘29%‘]]

# #***********************发送电子邮件*******************************
#第三方SMTP服务器

def sendEmail():
    msg=MIMEText(mail_msg,"html","utf-8")
    msg["From"]=formataddr(["裤裆人",mail_user])
    msg["To"]=formataddr(["小裤裆人s",receive_address])
    msg["Subject"]="北京天气预报"
    try:
        smtp0bj=smtplib.SMTP_SSL(mail_host,465)
        smtp0bj.login(mail_user,mail_pass)
        smtp0bj.sendmail(mail_user,receive_address,msg.as_string())
        smtp0bj.quit()
        print("mail has been send to %s successfully."%receive_address)
    except smtplib.SMTPException as e:
        print(e)

if __name__=="__main__":
    weather=get_weather("http://www.weather.com")
    weathers=get_5weathers("https://weather.com/zh-CN/weather/5day/l/CHXX0008:1:CH")
    if weather==None:
        exit()
    if weathers==None:
        exit()
    mail_host="smtp.163.com"
    mail_user="150XXxX[email protected]"    #发件人邮箱账号
    mail_pass="jXXxX199XXxX"          #发件人邮箱密码
    receives=[
              "4352XXxX@qq.com",
              "3426XXxX@qq.com",
              "5437XXxX[email protected]",
              "6353XXxX[email protected]",
             ]    #收件人邮箱账号
    mail_msg="""
    <h1>裤裆人天气预报</h1>
    <p style="color:#99cc00;font-size:15px">%s-->目前天气状况:温度%s ,%s ,%s ,%s </p>
    <h3>以下是未来5天的天气情况</h3>
    <table width="800px" border="0" cellspacing="1" cellpadding="0" style="text-align:center">
    <thead style="background-color:#3399ff">
        <tr style="line-height:40px;">
            <th>白天</th>
            <th>说明</th>
            <th>高/低</th>
            <th>降雨概率</th>
            <th>风力</th>
            <th>湿度</th>
        </tr>
    </thead>
    <tbody>
        <tr style="background: #ccffcc">
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
        </tr>
        <tr style="background: #ccffcc">
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
        </tr>
        <tr style="background: #ccffcc">
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
        </tr>
        <tr style="background: #ccffcc">
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
        </tr>
        <tr style="background: #ccffcc">
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
        </tr>
    </tbody>
</table>
<p style="color:red;font-size:10px">注意:每天早上八点准时发送邮件,希望小伙伴们,多多关注天气情况,注意保暖!</p>

"""%(weather[0],weather[1],weather[2],weather[3],weather[4],weathers[0][0],weathers[0][1],weathers[0][2],weathers[0][3],weathers[0][4],weathers[0][5],weathers[1][0],weathers[1][1],weathers[1][2],weathers[1][3],weathers[1][4],weathers[1][5],weathers[2][0],weathers[2][1],weathers[2][2],weathers[2][3],weathers[2][4],weathers[2][5],weathers[3][0],weathers[3][1],weathers[3][2],weathers[3][3],weathers[3][4],weathers[3][5],weathers[4][0],weathers[4][1],weathers[4][2],weathers[4][3],weathers[4][4],weathers[4][5])
    for receive_address in receives:
        sendEmail()
        time.sleep(120)
    exit()

原文地址:https://www.cnblogs.com/kudangren/p/lei.html

时间: 2024-08-28 14:05:25

python获取天气状况并以邮件的形式发到目的邮箱的相关文章

逗比学树莓派之用树莓派获取天气状况

在树莓派上我们可以通过"wether"工具来以命令行的方式获取天气预报信息. 首先当然是安装Weather工具,通过命令行 sudo apt-get install weather-util 安装结束后便可以通过不通的方式获取天气预报了. 最简单的获取天气状况的方法是使用ICAO代码(International Civil Aviation Organization Airport Code,国际民间航空组织机场代码,译注)查询最近的机场.所以要获取位于纽约的肯尼迪国际机场的天气你可以

关于TD邮件功能不能发到认证邮箱的解决之法

[原创] 关于TD邮件功能不能发到认证邮箱的解决之法 认证邮箱, 邮件服务器, 用户, 邮件系统 鉴于不少同行询问TD发邮件的问题,今天重新更新一下说明解决问题的原则如下一.在TD服务器上安装一个邮件服务器软件,该软件要带转发或者中继功能的,把转发/中继的地址设置为收邮件系统的某一个用户的信息,具体邮件服务器配置请参考相关资料,我第一次配置成功是在2006年5月初配置成功,采用的是遥志邮件服务器软件,后来改用MailDirect.二.配置好邮件服务器后要设置好TD与邮件服务器的连接,具体方法请参

根据IP获取天气状况

上一节我们学习了如何获取客户端IP,并确定其所在地.这一节我们接着学习根据已获取的信息进一步获取客户所在地的天气情况. 根据上一节里我们已经获取了的客户所在的省份.城市,那么我们只要利用一些与天气相关的网站的API,就能完成天气情况的信息获取(此处使用的是中国天气网所提供的API). 我们还是先来看看代码怎么实现的: <?php header('Content-Type:text/html;Charset=utf-8'); function GetIp(){ $realip = ''; $unk

python获取天气+email通知

信息抓取来源: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 = '[em

Python 获取zabbix数据图并发邮件

#! /usr/bin/env python # coding=utf-8 # Andy_f import time, os,datetime import urllib import urllib2 import cookielib import MySQLdb import smtplib from email.mime.multipart import MIMEMultipart  # 导入MIMEMultipart类 from email.mime.text import MIMETex

python获取天气以及地理信息

一.寻找需要用到的API 在我努力查找之下,我找到了和风天气这个强大又方便的API.接着在平台上注册登录,得到你所需要的key,留以接下来使用 二.用requests获取所需要的数据 根据免费版的url获取 url = "https://free-api.heweather.net/s6/weather/%s?location=%s&key=%s" % (weather_type, parameters, key) page = requests.get(url) page =

python获取外网IP并发邮件

第一步:通过ip138来爬取外网ip 第二部:通过python的smtplib模块和email来发送邮件,具体用法去网上搜索,下面是代码示例: #!/usr/bin/env python #coding:utf-8 import urllib2 import re import smtplib from email.MIMEText import MIMEText from email.Header import Header ##################################

python 获取天气信息

[说明]接口为聚合数据接口.API使用说明: 实现代码: import requests,json def main(): #参数 farmat=1 cityname = input("请输入你想查询的城市天气:") key='621043608cb9e7f7f485461ef9e5adef' get_weather(farmat,cityname,key) def get_weather(format,cityname,key): url='http://v.juhe.cn/weat

使用Python获取各个城市当前的天气情况

这次的这个项目,弄了好几天,主要在tkinter上做GUI界面上一直卡住,在网上资料又不多,最后直接放弃稍微复杂的东西,直接做个简单点的界面. 程序功能: 1.可以查询不同城市的天气情况和显示时间,每60秒刷新次天气情况,如图:2.可以自由选择城市,选择之后立刻获取该城市的天气情况 关键代码 # _*_ coding: utf-8 _*_ import requests import time def weather_log(stu): #获取实时天气情况写入到文本 cu_time=time.s