BeautifulSoup爬取天气信息并发送给微信好友

本文介绍了一个使用Python的BeautifulSoup库从特定网站抓取天气信息的方法,并通过wxpy库将这些信息自动推送到指定的微信好友。代码实现了获取当前及未来一天的天气状况、温度、风速和空气质量等详细信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

"""
    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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值