"""
BeautifulSoup爬取天气信息并发送给微信好友
"""
import datetime
from wxpy import *
from bs4 import BeautifulSoup
from urllib import request
bot = Bot(cache_path=True) # 登陆网页微信,并保存登陆状态
def send_message(content):
"""发送信息"""
my_friend = bot.friends().search(u'老婆')[0] # 搜索好友
my_friend.send(content)
# my_group = bot.groups().search(u'lol')[0] # 搜索群组
# my_group.send(content)
def weather_spider():
"""获取天气信息"""
url = "https://tianqi.moji.com/weather/china/chongqing/nan'an-district"
html = request.urlopen(url).read().decode('utf-8')
soup = BeautifulSoup(html, 'lxml')
weather = soup.find('div', attrs={'class': "wea_weather clearfix"})
# 获取今日天气
temperature1 = weather.find('em').get_text()
weather1 = weather.find('b').get_text()
hot_tip = soup.select(".wea_tips.clearfix em")[0].get_text() # 今日天气提示
data = str(datetime.date.today()) # 获取当天日期
info_j = '小姐姐您好:\n' + data + '\n重庆市南岸区\n实时温度:' + temperature1 + '℃' + ',' + weather1 + '。' + '\n特别提示:' + hot_tip
# 获取明日天气
tomorrow = soup.select(".days.clearfix ")[1].find_all('li')
temperature2 = tomorrow[2].get_text().replace('°', '℃') + ',' + tomorrow[1].find('img').attrs['alt'] # 明日温度
s_t1 = tomorrow[3].find('em').get_text()
s_t2 = tomorrow[3].find('b').get_text()
s_t = s_t1 + s_t2 # 明日风速
aqi_t = tomorrow[-1].get_text().strip() # 明日空气质量
info_m = '\n明日天气:\n' + '温度:' + temperature2 + '\n' + '风速:' + s_t + '\n' '空气质量:' + aqi_t + '\n'
info = info_j + '\n' + info_m
send_message(info)
weather_spider()