因为之前使在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')