python通过微信给她发送每日天气
因为之前使在Python中使用BeautifulSoup时,会出现no attribute的报错,所以我就决定不使用BeautifulSoup组件,只通过使用wxauto达到自动发送的目的。利用简单的爬虫就可以实现。
这里使用的天气网站是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 = 【今日天气预报】 +
+ parent + city + " " + time + "
"
+ "更新时间:" + week + " " + updateTime + "
"
+ "当前温度:" + wendu + "℃" + "
"
+ "天气:" + wtype + "
"
+ "温度范围:" + low + "~" + high + "
"
+ "空气湿度:" + shidu + "
"
+ "风向:" + fx + "
"
+ "风力:" + fl +
+ "空气质量:" + quality +
+ "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)
下一篇:
java失物招领及估价拍卖系统
