【代码DIY】之爬取天气信息并利用twilio发送短信

说明 📘
  • 太久没更博了,罪过罪过🙏;
  • 最近天气转凉,遂想每天给自己的家人朋友定时发一些天气问候。一开始是想每天定时发送微信消息来提醒,但微信API好像不能用了;
  • 因此,只能利用短信来发送了,几番搜寻后,便发现twilio可以实现这个功能。
  • 实现步骤:
  • 首先爬取墨迹天气相关信息;
  • 再个性化处理信息;
  • 最后调用 twilio API 以短信形式发送之。
  • 声明:所写代码有参考部分网络上的部分代码,鉴于时间缘故,忘记最初来源了😂。知情者,忘告之,侵删!
代码DIY 🔎
  • 主体部分
from twilio.rest import Client

# "xxxxx"部分填写你在twilio上注册的id和token
def client_config(account_sid='xxxxxxxxxxxxxxxx', auth_token='xxxxxxxxxxxxxxx'):
    account_sid = account_sid
    auth_token = auth_token
    _client = Client(account_sid, auth_token)
    return _client


# 编辑好所发送信息
def format_msg(_info, _name):
    _msg = '❤❤❤❤❤❤❤❤❤❤❤\n' + 'Dear {}: \n以下是'.format(_name) + _info + '❤❤❤❤❤❤❤❤❤❤❤'
    return _msg


# 发送短信
def send_message(_client, _msg, _name):
    # 填写twilio上的 Trial Number
    message = _client.messages.create(body=_msg, from_='+xxxxxx', to=name_phone_dict[_name])
    print(message.sid)
    print("发送成功!")


if __name__ == "__main__":
    # 获取天气信息
    prov_city_tuple = [("湖北", "武汉"), ("重庆", "重庆"), ("广东", "惠州"), ("四川", "成都")]
    city_name_dict = {"武汉": ['xkw', 'qqx'], "重庆": ['xxw'], "惠州": ['qdw'], "成都": ['xxw']}
    name_phone_dict = {'xkw': '+86159xxxxxxxx', 'qqx': '+86139xxxxxxxx', 'xxw': '+86186xxxxxxxx'}
    # 存储对应城市的天气信息
    msg_dict = {}
    # 默认参数就是账户id和账户token
    msg_client = client_config()
    for prov, city in prov_city_tuple[:1]:
        url = init_city(prov, city)
        info = get_info(url, prov, city)
        for name in city_name_dict[city]:
            msg = format_msg(_info=info, _name=name)
            msg_dict[prov] = msg
            print(msg_dict[prov])
            # 发送个性化天气相关信息
            send_message(_client=msg_client, _msg=msg, _name=name)
            print("\n********************************************************\n")

  • 主体部分所调函数
  • 爬取天气相关信息
from xpinyin import Pinyin
from urllib import request
from bs4 import BeautifulSoup
import datetime


def init_city(prov, city):
    prov = prov
    city = city
    pin = Pinyin()

    prov_pin = pin.get_pinyin(prov, '')
    city_pin = pin.get_pinyin(city, '')

    url = "https://tianqi.moji.com/weather/china/"
    # "爬取天气信息时,重庆这个城市需要特别处理"
    if prov == "重庆":
        url = "https://tianqi.moji.com/weather/china/chongqing/chongqing"
    else:
        url = url + prov_pin + '/' + city_pin
    print(url)
    return url


def get_info(url, prov, city):
    # 获取天气信息
    htmlData = request.urlopen(url).read().decode('utf-8')
    soup = BeautifulSoup(htmlData, 'lxml')
    weather = soup.find('div', attrs={'class': "wea_weather clearfix"})
    temp1 = weather.find('em').get_text()
    temp2 = weather.find('b').get_text()
    # 使用select标签时,如果class中有空格,将空格改为“.”才能筛选出来
    # 空气质量 AQI
    AQI = soup.select(".wea_alert.clearfix > ul > li > a > em")[0].get_text()
    H = soup.select(".wea_about.clearfix > span")[0].get_text()     # 湿度
    S = soup.select(".wea_about.clearfix > em")[0].get_text()       # 风速

    A = soup.select(".wea_tips.clearfix em")[0].get_text()          # 今日天气提示
    U = soup.select(".live_index_grid > ul > li")[-3].find('dt').get_text()     # 紫外线强度

    # print("\n相关信息:\n", AQI, H, S, A, U)

    # DATE = str(datetime.date.today())       # 获取当天日期 ****-**-**
    DATE = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

    if prov == '重庆':
        info = '来自 xkw 的天气问候\n' + city + '市' + ',' + DATE + '\n' + '实时温度:' + temp1 + '℃' + ',' + \
               temp2 + '\n'  '湿度:' + H + '\n' '风速:' + S + '\n' '紫外线:' + U + '\n' '今日提示:' + A + "\n"
    else:
        info = '来自 xkw 的天气问候\n' + prov + '省' + city + '市' + ',' + DATE + '\n' + '实时温度:' + temp1 + '℃' + ',' +\
               temp2 + '\n'  '湿度:' + H + '\n' '风速:' + S + '\n' '紫外线:' + U + '\n' '今日提示:' + A + "\n"

    # print(info)

    # 获取明日天气
    tomorrow = soup.select(".days.clearfix ")[1].find_all('li')
    # <img alt=*****   src="*************************.jpg">标签的查找
    temp_t = tomorrow[2].get_text().replace('°', '℃') + ',' + tomorrow[1].find('img').attrs['alt']  # 明日温度
    S_t1 = tomorrow[3].find('em').get_text()
    S_t2 = tomorrow[3].find('b').get_text()
    S_t = S_t1 + S_t2                           # 明日风速
    AQI_t = tomorrow[-1].get_text().strip()     # 明日空气质量
    info_t = '\n明日天气:\n' + '温度:' + temp_t + '\n' + '风速:' + S_t + '\n' '空气质量:' + AQI_t + '\n'

    # 获取生活tips
    tips_dict = {'cold': '感冒预测', 'makeup': '化妆指数', 'uray': '紫外线量', 'dress': '穿衣指数',
                 'car': '关于洗车', 'sport': '运动事宜'}
    info_tips = ''
    for i in list(tips_dict.keys()):
          url_tips = url.replace('weather', i)
          htmlData = request.urlopen(url_tips).read().decode('utf-8')
          soup = BeautifulSoup(htmlData, 'lxml')
          tips = soup.select(".aqi_info_tips > dd")[0].get_text()
          info_tips = info_tips + tips_dict.get(i) + ': ' + tips + '\n'

    info_all = info + '\n' + info_tips + info_t
    return info_all

结果展示 💦
❤❤❤❤❤❤❤❤❤❤❤
Dear xkw: 
以下是来自 xkw 的天气问候
湖北省武汉市,2019-12-27 10:45
实时温度:6℃,晴
湿度:湿度 82%
风速:东南风2级
紫外线:适宜
今日提示:天气阴冷,穿暖和点吧!

感冒预测: 感冒极易发生,避免去人群密集的场所,勤洗手勤通风有利于降低感冒几率。
化妆指数: 天气寒冷,多补水,选用滋润保湿型化妆品,使用润唇膏。
紫外线量: 涂擦SPF大于15、PA+防晒护肤品。
穿衣指数: 天气偏凉,可以穿上最时尚的那件大衣来凹造型,搭一条围巾时尚指数爆表。
关于洗车: 洗车后,只能保持1天车辆清洁,不太适宜洗车。
运动事宜: 空气轻度污染,不宜在户外运动。
明日天气:
温度:3℃ / 7℃,小雨
风速:东南风3级
空气质量:95 良
❤❤❤❤❤❤❤❤❤❤❤
The End 🎈
  • PS: 还是希望能以微信形式发送,解决方案尚未找到;
  • 最近twilio发送短信存在接受不到信息的情况,有解决方案的小伙伴还请不吝赐教啊~
  • 更多爬虫项目:GitHub
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值