每天发送天气预报

本文介绍了一个使用Python编写的自动化天气通知系统,该系统能够定时抓取指定城市的PM2.5、AQI指数、空气质量等级及温度等信息,并通过微信自动发送给设定的联系人。系统利用urllib.request进行网页请求,BeautifulSoup解析网页内容,itchat实现微信消息发送,schedule安排定时任务。

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

#weather.py
#coding=utf8
import urllib.request
from time import ctime
from bs4 import BeautifulSoup
import itchat
import schedule, time

class Weather():
    itchat.auto_login(hotReload=True)

    def sel(self):
        self.getPM25("地址","备注名")

    def get_soup(self,site):
        page = urllib.request.urlopen(site)
        html = page.read()
        soup = BeautifulSoup(html.decode("utf-8"), "html.parser")
        return soup

    def getPM25(self,cityname,friend):
        site = 'http://www.pm25.com/' + cityname + '.html'
        soup = self.get_soup(site)
        city = soup.find(class_='bi_loaction_city')  # 城市名称
        aqi = soup.find("a", {"class", "bi_aqiarea_num"})  # AQI指数
        quality = soup.select(".bi_aqiarea_right span")  # 空气质量等级
        result = soup.find("div", class_='bi_aqiarea_bottom')  # 空气质量描述
        temp = soup.find("p",{"class","bi_info_weather"})  #温度
        tempFrom = soup.find("p",{"class","bi_info_tips"}) #数据来源
        hr = soup.findAll("a", {"class", "iml_yinshi_right_oneitem_title"})[0]
        # soup = self.get_soup(hr["href"])
        # content = ''
        # question = hr.text
        # titles = soup.findAll("strong")
        # for title in titles:
        #     content = content + "\n" + title.text.strip()
        # article = question + "\n" + content
        output=city.text+ u'\n温度:' + temp.text + u'\nAQI指数:' + aqi.text + u'\n空气质量:' + quality[0].text + result.text + '\n' + tempFrom.text
        print(output)
        user = itchat.search_friends(friend)
        username = user[0]["UserName"]
        itchat.send(output,username)
        print('*' * 20 + ctime() + '*' * 20)

if __name__ == '__main__':
    weather = Weather()
    schedule.every().day.at("08:10").do(weather.sel)
    #schedule.every(10).minutes.do(weather.sel)
    while True:
        schedule.run_pending()
        time.sleep(1)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

young_kp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值