python通过微信给她发送每日天气

因为之前使在Python中使用BeautifulSoup时,会出现no attribute的报错,所以我就决定不使用BeautifulSoup组件,只通过使用wxauto达到自动发送的目的。利用简单的爬虫就可以实现。

使用的模块主要有以下几个:通过使用Python中的requests、json、wxauto、wxpy库实现发送每日天气到电脑微信。

这里使用的天气网站是http://t.weather.sojson.com/api/weather/city/城市代号

城市代号可以通过这个链接到达天气预报

代码如下

import json
import requests
from wxauto import WeChat
from wxpy import ResponseError


def get_weather():
    url = 'http://t.weather.sojson.com/api/weather/city/城市代码'
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36'
    }

    rep = requests.get(url, headers=header)
    rep.encoding = "utf-8"
    weather = rep.text
    weather = json.loads(weather)

    time = weather['time']  # 时间
    parent = weather['cityInfo']['parent']  # 所属城市
    city = weather['cityInfo']['city']  # 城区
    updateTime = weather['cityInfo']['updateTime']  # 更新时间
    shidu = weather['data']['shidu']  # 湿度
    pm25 = weather['data']['pm25']  # PM2.5
    quality = weather['data']['quality']  # 空气质量
    wendu = weather['data']['wendu']  # 当前温度
    low = weather['data']['forecast'][0]['low']  # 今日最低温
    high = weather['data']['forecast'][0]['high']  # 今日最高温
    week = weather['data']['forecast'][0]['week']  # 星期
    fx = weather['data']['forecast'][0]['fx']  # 风向
    fl = weather['data']['forecast'][0]['fl']  # 风力
    wtype = weather['data']['forecast'][0]['type']  # 天气

    result = '【今日天气预报】' + '\n' \
             + parent + city + "  " + time + "\n" \
             + "更新时间:" + week + "  " + updateTime + "\n" \
             + "当前温度:" + wendu + "℃" + "\n" \
             + "天气:" + wtype + "\n" \
             + "温度范围:" + low + "~" + high + "\n" \
             + "空气湿度:" + shidu + "\n" \
             + "风向:" + fx + "\n" \
             + "风力:" + fl + '\n' \
             + "空气质量:" + quality + '\n' \
             + "PM2.5:" + str(pm25)

    return result


if __name__=='__main__':
    try:
        wx = WeChat()
        wx.GetSessionList()
        weather = get_weather()
        msg = weather
        who = 'XXX'
        wx.ChatWith(who)
        wx.SendMsg(msg)
    except ResponseError as e:
        print('error')

 

 

  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值