上次和大家分享了爬取天气信息的python程序,程序上还有很多缺点,需要再了解一些html和css等相关知识后,才会把爬虫的程序做的更好。
我们爬取到天气数据之后,接下来应该做些什么有趣的事情的呢?我们可以把这些天气数据发送给父母和微信好友~若要实现后面的功能,我们可以使用python的wxpy模块和wechat_sender模块。一直以来都希望可以把程序的一些功能关联到生活中,到现在,这个愿望终于要达成了。
程序平台:ubuntu16.04(x86)、python3.7
Python3.7相关模块的安装:
sudo python3.7 -m pip install wxpy
其他模块以此类推
一、 Wechat_Sender介绍
随时随地发消息到微信。wechat_sender 是基于 wxpy 和 tornado 实现的一个可以将你的网站、爬虫、脚本等其他应用中各种消息 (日志、报警、运行结果等) 发送到微信的工具。
使用起来也很方便,监听侧Bot()初始化后,使用listen()监听,手机端扫码登录后,就可以使用wechat_sender的Sender()进行发送消息了。
1. Bot程序:
# coding: utf-8
from __future__ import unicode_literals
from wxpy import *
from wechat_sender import listen
bot = Bot(‘bot.pkl’)
receivers = []
receivers.append(bot.file_helper)
#receivers.append(bot.friends().search('dapi')[0]) #多个接收者
#receivers.append(bot.friends().search('家_妈妈')[0])
print(receivers)
listen(bot, receivers = receivers) #将Send()发送的消息发送给receivers
2. Sender侧程序
# coding: utf-8
from wechat_sender import Sender
Sender().sender(‘hello world’)
登录结果:
微信文件助手接收结果:
二、 发送爬取天气的结果
爬取天气结果组装数据成字典,然后再将字典拆解成字符串进行发送。
# coding: utf-8
import requests
from bs4 import BeautifulSoup
import re
from wechat_sender import Sender
def getWeath(city_code):
try:
print(city_code)
url = 'http://www.weather.com.cn/weather/%s.shtml'%city_code
ret = requests.get(url)
except BaseException as e:
print(e)
return {}
ret.encoding = 'utf-8'
soup = BeautifulSoup(ret.text, 'html.parser')
tagToday = soup.find('p', class_ = "tem") #第一个包含class="tem"的p标签即为存放今天天气数据的标签
try:
temperatureHigh = tagToday.span.string #有时候这个最高温度是不显示的,此时利用第二天的最高温度代替。
except AttributeError:
temperatureHigh = tagToday.find_next('p', class_="tem").span.string #获取第二天的最高温度代替
temperatureLow = tagToday.i.string #获取最低温度
weather = soup.find('p', class_ = "wea").string #获取天气
wind = soup.find('p', class_ = "win") #获取风力
clothes = soup.find('li', class_ = "li3 hot") #穿衣指数
#print('最低温度:' + temperatureLow)
#print('最高温度:' + temperatureHigh)
#print('天气:' + weather)
#print('风力:' + wind.i.string)
#print('穿衣:' + clothes.a.span.string + "," + clothes.a.p.string)
return {'温度':temperatureHigh + '/' + temperatureLow
, '天气':weather
, '风力':wind.i.string
, '穿衣':clothes.a.span.string + ',' + clothes.a.p.string}
def strDic(dic):
str_weather = ''
for key in dic:
str_weather += key + ':' + dic[key]
str_weather += '\n'
return str_weather
if __name__ == "__main__":
wea_str = strDic(getWeath(101100701))
Sender().send(wea_str)
结果如图: