通过爬虫定期发送当地天气情况给自己的邮箱

代码实现

这里爬取天气信息比较简单所以就直接附上代码了

import smtplib
from email.header import Header
from email.mime.text import MIMEText

import requests
from lxml import etree


# 获取当天的天气情况
def ForWeather(weather_list):
    today=[]
    for weather in weather_list:
        dic={}
        #标题
        weather_title=weather.xpath('./h1/text()')[0]
        #天气
        wea=weather.xpath('./p[@class="wea"]/@title')[0]
        sky=weather.xpath('string(./div[@class="sky"])')
        #温度
        tem=weather.xpath('string(./p[@class="tem"])')
        #风速
        win=weather.xpath('./p[@class="win"]/span/@title')[0]
        speed=weather.xpath('./p[@class="win"]/span/text()')[0]
        sun=weather.xpath('string(./p[4])').strip()
        dic['weather_title']=weather_title
        dic['wea']=wea
        dic['sky']=sky.replace("\n"," ")
        dic['tem']=tem.strip()
        dic['win']=win
        dic['speed']=speed
        dic['sun']=sun
        today.append(dic)
    return today
#获取当天生活指数
def IndexForLife(life_list):
     life={}
     #中暑指数
     heatstroke='\n'.join([life_list[0].xpath('.//span/text()')[0],"推荐:"+life_list[0].xpath('.//p/text()')[0]])
     #减肥指数
     reduce_weight  = '\n'.join([str(len(life_list[1].xpath('.//span/em')))+"颗星", "推荐:"+life_list[1].xpath('.//p/text()')[0]])
     #血糖指数
     blood_sugar='\n'.join([life_list[2].xpath('.//span/text()')[0],"推荐:"+life_list[2].xpath('.//p/text()')[0]])
     #穿衣指数
     dress = '\n'.join([life_list[3].xpath('.//span/text()')[0],"推荐:"+life_list[3].xpath('.//p/text()')[0]])
     #洗车指数
     wish_car = '\n'.join([life_list[4].xpath('.//span/text()')[0], "推荐:"+life_list[4].xpath('.//p/text()')[0]])
     #紫外线指数
     ultraviolet = '\n'.join([life_list[5].xpath('.//span/text()')[0],"推荐:"+ life_list[5].xpath('.//p/text()')[0]])
     life['heatstroke']=heatstroke
     life['reduce_weight']=reduce_weight
     life['blood_sugar']=blood_sugar
     life['dress']=dress
     life['wish_car']=wish_car
     life['ultraviolet']=ultraviolet
     return life
# 获取当天的天气情况
def GetOnSameDayWeather():
    url='http://www.weather.com.cn/weather1d/101250101.shtml'
    rep=s.get(url).content.decode(encoding='utf-8')
    tree=etree.HTML(rep)
    weather_list=tree.xpath('//ul[@class="clearfix"]/li')[:2]
    life_list=tree.xpath('//ul[@class="clearfix"]/li')[2:]
    #获取当天白天和夜间天气情况
    today=ForWeather(weather_list)
    #获取当天生活指数
    life=IndexForLife(life_list)
    result=''
    for t in today:
        result+=f'' \
                f'时间点:{t["weather_title"]}\n' \
                f'天气:{t["wea"]}\n' \
                f'天空:{t["sky"]}\n' \
                f'平均温度:{t["tem"]}\n' \
                f'风速:{t["win"]}:{t["speed"]}\n' \
                f'日出/日落:{t["sun"]}\n'
    result +=f'' \
             f'中暑指数:{life["heatstroke"]}\n'\
             f'减肥指数:{life["reduce_weight"]}\n'\
             f'血糖指数:{life["blood_sugar"]}\n'\
             f'穿衣指数:{life["dress"]}\n'\
             f'洗车指数:{life["wish_car"]}\n'\
             f'紫外线指数:{life["ultraviolet"]}\n'
    return result
# 获取七天内的天气情况
def ForSevenDaysWeather():
    url = 'http://www.weather.com.cn/weather/101250101.shtml'
    rep = s.get(url).content.decode(encoding='utf-8')
    tree = etree.HTML(rep)
    weather_list = tree.xpath('//ul[@class="t clearfix"]/li')
    week=[]
    for li in weather_list:
        dic = {}
        #时间
        day=li.xpath('./h1/text()')[0]
        # 天气
        wea = li.xpath('./p[@class="wea"]/@title')[0]
        # 温度
        tem = li.xpath('string(./p[@class="tem"])')
        # 风速
        win = li.xpath('./p[@class="win"]//span/@title')[0]
        speed = li.xpath('./p[@class="win"]/i/text()')[0]
        dic['day'] = day
        dic['wea'] = wea
        dic['tem'] = tem.strip()
        dic['win'] = win
        dic['speed'] = speed
        week.append(dic)
    result=''
    for t in week:
        result += f'' \
                  f'时间点:{t["day"]}\n' \
                  f'天气:{t["wea"]}\n' \
                  f'平均温度:{t["tem"]}\n' \
                  f'风速:{t["win"]}:{t["speed"]}\n'+'-'*50+'\n'
    return result
#发送邮件
def sendEmail(content,title):
    sender="自己的163邮箱"
    receivers=["*****@qq.com"]
    mail_host = "smtp.163.com"
    mail_pass="密码"
    message = MIMEText(content, 'plain', 'utf-8')  # 内容, 格式, 编码
    message['From'] = "{}".format(sender)
    message['To'] = ",".join(receivers)
    message['Subject'] = title
    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
        smtpObj.login(sender, mail_pass)  # 登录验证
        smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
        print("mail has been send successfully.")
    except smtplib.SMTPException as e:
        print(e)

if __name__ == '__main__':
    s = requests.session()
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36 Maxthon/5.2.6.1000",
    }
    # 获取当天的天气情况
    Today_result=GetOnSameDayWeather()
    #发送邮箱
    sendEmail(Today_result,'今日天气情况')
    # 获取七天内的天气情况
    Week_result=ForSevenDaysWeather()
    # 发送邮箱
    # sendEmail(Week_result,'一周的天气情况')

如果出现什么问题邮箱发送失败,可能用qq邮箱发给163邮箱

window设置定时任务

打开管理

使用快捷键“windows+r”打开运行指令框。
在这里插入图片描述
输入:compmgmt.msc
在这里插入图片描述

创建基本任务

在这里插入图片描述

填写信息

在这里插入图片描述

定义开始时间(用户根据需求来定)

在这里插入图片描述
在这里插入图片描述

选择

在这里插入图片描述

点完成

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫可以用来抓取网页数据,包括西藏地区的天气情况。不过请注意,直接爬取网站的数据可能涉及到隐私和版权问题,最好先确认目标网站的Robots协议,以及是否允许爬虫访问。以下是一个基本的步骤来使用Python(比如使用`requests`和`BeautifulSoup`库)来获取天气信息: 1. 寻找API或提供数据的稳定源:有些天气预报网站可能提供了API服务,可以直接调用获取数据,例如中国气象局的API(http://data.cma.cn/)或者第三方天气服务提供商。 2. 如果没有API,可能需要解析HTML:使用`requests`库获取网页内容,然后使用`BeautifulSoup`或`lxml`等库解析HTML,找到包含天气信息的部分。 3. 数据提取:定位到天气预报、温度、日期等关键信息元素,并提取出来。 4. 存储或处理数据:将提取的数据存储到本地文件或者数据库中,也可以进一步分析和可视化。 以下是一个简单的示例代码片段(假设使用了第三方API): ```python import requests # 假设使用了requests_weather库,实际使用请根据实际情况替换 response = requests.get("https://api.weather.com/v3/wx/forecast/daily/point/TIBA:0,91.12") data = response.json() # 提取天气数据 temperature = data['forecasts']['temperature'] description = data['forecasts']['text'] print(f"西藏拉萨的天气情况:{description}, 温度:{temperature}") # 注意:以上代码是假设的,实际操作请根据API文档进行 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值