以前在浏览网站的时候发现了篇文章「玩转树莓派」为女友打造一款智能语音闹钟,文章中介绍了使用树莓派打造一款语音播报天气的闹钟。html
当时就想照着来,也本身作个闹钟。由于一直没有买到树莓派(主要是想不起来买),这件事就搁浅了。虽然硬件没有,但能够用微信啊。python
下面开始正文部分。微信
目前只是最第一版本,只获取了当前的日期、天气情况、气温、风向和风力这五个信息。以上信息都是从中国天气网获取的。网站
上码:编码
from bs4 import BeautifulSoup from urllib.request import urlopen def get_weather(url): #url = 'http://www.weather.com.cn/weather/101210402.shtml' html = urlopen(url).read().decode('utf-8') # print(html) soup = BeautifulSoup(html, features='lxml') today = soup.find('li', attrs={'class': 'sky skyid lv1 on'}) # print(today) day = today.find('h1').get_text() # print(day.get_text()) weather = today.find('p', {'class': 'wea'}).get_text() # print(weather.get_text()) temp = today.find('p', {'class': 'tem'}).get_text()[1:-1] # print(temp.get_text()) windy = today.find('p', {'class': 'win'}).find('em').find_all('span') windy = windy[0]['title']+'转'+windy[1]['title'] # print(windy) windy_power = today.find('p', {'class': 'win'}).find_all('i')[0].get_text() # print('风力:',windy_power.get_text()) return day, weather, temp, windy, windy_power
get_weather()的参数是包含要查询地区的地区编码的URL连接,使用你要查询的地区编码替换实例中的“101210402”便可。关于地区编码的获取我这里提供两种方法:一种是从网上找现成的,另外一种中就是在天气网上输入地区而后获得URL。我的推荐第二种方法,由于这样能够查到县/区这一级别。url
itchat是一个开源的微信我的号接口,使用Python调用微信从未如此简单。关于项目的详细介绍和使用,请看这里。spa
上码:code
import itchat import weather_tools def send_weather(url): # 获取天气信息 day, weather, temp, windy, windy_power = weather_tools.get_weather(url) # 拼接消息 msg = '今日天气:\n时间:{}\n天气:{}\n气温:{}\n风向:{}\n风力:{}' msg = msg.format(day, weather, temp, windy, windy_power) # 登陆微信 itchat.auto_login(True) # 发送消息 itchat.send(msg, toUserName='filehelper') # 退出登陆 itchat.logout() if __name__ == "__main__": url = 'http://www.weather.com.cn/weather/101210402.shtml' send_weather(url)
send_weather()是向 文件助手发送当天的天气情况,‘filehelper’表明微信中的文件助手。orm