爬取天气信息通过邮箱定时发送

爬取天气信息通过邮箱定时发送

  1. 准备事项:

    演示网址:http://www.weather.com.cn/weather1d/101281905.shtml
    运行库版本
    beautifulsoup=4 4.9.3
    requests= 2.25.1
    schedule =1.0.0

    准备好需要的库

    pip install xxx

    需要用到的库

    import requests
    import smtplib
    import schedule
    import time
    from bs4 import BeautifulSoup
    from email.mime.text import MIMEText
    from email.header import Header
    
  2. 进入到该网址确定要爬取的信息

    image-20210323110220772

    image-20210323110437659)

  3. 确定好游览器打开开发者工具确定我们要爬取的信息的标签位置点击小箭头

    1

  4. 通过上一步操作我们可以发现天气标签被包裹在ul标签里面

    headers={
        'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }
    #防止反爬,伪装成游览器请求头
    url='http://www.weather.com.cn/weather1d/101281905.shtml'
    res=requests.get(url,headers=headers)
    #打印返回状 态码200为成功
    print(res.status_code)
    res.encoding='utf-8' #把获取到信息设置为utf-8
    
    #利用BeautifulSoup解析数据
    soup=BeautifulSoup(res.text,'html.parser')
    #找到需要的度数和天气状况的父标签
    wea1=soup.find('div',class_='t').find('ul',class_='clearfix')
    #从父标签找到需要的度数
    wea=wea1.find('p',class_='tem').text
    weather=wea1.find('p',class_='wea').text
    print(wea)#打印测试
    print(weather)#打印测试
    

    image-20210323123223299

  5. 接下来爬取生活指数

    2

    分析:

    image-20210323130703858

    因为单纯找clearfix标签是找不到生活指数的 有多个 所以定位父标签要往上一级但是上一级也有多个left-div

    BeautifulSoup的find_all方法返回的是一个列表 也就是我们想要的数据在列表的第4个 也就是下标为3

  6. 还是要找到离要的数据 他们共同的父标签

    直接上代码

    headers={
        'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }
    #防止反爬,伪装成游览器请求头
    url='http://www.weather.com.cn/weather1d/101281905.shtml'
    res=requests.get(url,headers=headers)
    #打印返回状 态码200为成功
    print(res.status_code)
    res.encoding='utf-8' #把获取到信息设置为utf-8
    
    #利用BeautifulSoup解析数据
    soup=BeautifulSoup(res.text,'html.parser')
    #找到需要的度数和天气状况的父标签
    wea1=soup.find('div',class_='t').find('ul',class_='clearfix')
    #找到需要的度数
    wea=wea1.find('p',class_='tem').text
    weather=wea1.find('p',class_='wea').text
    print(wea)
    print(weather)
    day= soup.find_all('div', class_='left-div')[3].find('ul', class_='clearfix')
    
    #衣物
    clothes = "\n" + "衣物:" + "\n" + day.find('li', id='chuanyi').find('a').text.strip()
    sun = day.find_all('li', class_='li1')
    #紫外线
    sun2 = "\n" + "紫外线:" + "\n" + sun[1].text.strip() + "\n"
    #不宜
    not_suitable= day.find('li', class_='li4').text.strip()
    print(sun2)
    print(clothes)
    print(not_suitable)
    

    image-20210323133036554

    image-20210323131902395

  1. 数据获取到了接下来用邮箱发送

    • 这里用QQ邮箱演示 发件邮箱必须开启smtp
    • 网页端邮箱点 --> 设置----> 账户
      image-20210323133555449
    • 必须是已开启
    • 成功之后会出现一个密码 那个密码就是用来发送邮件的密码 不是原本QQ邮箱的密码
  2. 直接上代码(封装为一个函数)参数是爬虫的 爬到的数据

    def send_email(tem,weather,clothes,sun2,hat):
        # 把qq邮箱的服务器地址赋值到变量mailhost上
        email='smtp.qq.com'
        # 实例化一个smtplib模块里的SMTP类的对象
        qqmail = smtplib.SMTP()
        #连接服务器,email是地址,25是SMTP端口号。
        qqmail.connect(email,25)
        #把录入的发件的账号 密码传入登录
        qqmail.login(account,password)
        #邮箱正文
        content= '今天的天气是:'+tem+weather+"\n"+clothes+"\n"+sun2+"\n"+hat
        # 实例化一个MIMEText邮件对象,写入邮件正文,文本格式和编码
        mess= MIMEText(content, 'plain', 'utf-8')
        subject = '今日天气预报'
        # 左边实例化一个Header邮件头对象,该对象需要写入两个参数,
        # 分别是邮件主题和编码,然后赋值给等号左边的变量mess['Subject']。
        mess['Subject'] = Header(subject, 'utf-8')
        try:
            qqmail.sendmail(account, receiver, mess.as_string())
            print ('邮件发送成功')
        except:
            print ('邮件发送失败')
        #退出    
        qqmail.quit()
    
  3. 定时

    schedule.every().day.at("07:00").do(job)  #每天7点执行一次任务
    schedule.every().Tuesday.at("12:00").do(job) #每个星期二的12:00开始一次任务
    
  4. 完整代码

    # -*- coding: utf-8 -*-
    
    import requests
    import smtplib
    import schedule
    import time
    from bs4 import BeautifulSoup
    from email.mime.text import MIMEText
    from email.header import Header
    
    account = input(str('请输入你的邮箱:'))
    password = input(str('请输入你的密码:'))
    receiver = input(str('请输入收件人的邮箱:'))
    
    headers={
        'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }
    def  weathers():
        #防止反爬,伪装成游览器请求头
        url='http://www.weather.com.cn/weather1d/101281905.shtml'
        res=requests.get(url,headers=headers)
        #打印返回状 态码200为成功
        #print(res.status_code)
        res.encoding='utf-8' #把获取到信息设置为utf-8
    
        #利用BeautifulSoup解析数据
        soup=BeautifulSoup(res.text,'html.parser')
        #找到需要的度数和天气状况的父标签
        wea1=soup.find('div',class_='t').find('ul',class_='clearfix')
        #找到需要的度数
        wea=wea1.find('p',class_='tem').text
        weather=wea1.find('p',class_='wea').text
        # print(wea)
        # print(weather)
        day= soup.find_all('div', class_='left-div')[3].find('ul', class_='clearfix')
    
        clothes = "\n" + "衣物:" + "\n" + day.find('li', id='chuanyi').find('a').text.strip()
        sun = day.find_all('li', class_='li1')
        sun2 = "\n" + "紫外线:" + "\n" + sun[1].text.strip() + "\n"
        #不宜
        not_suitable= day.find('li', class_='li4').text.strip()
        # print(sun2)
        # print(clothes)
        # print(not_suitable)
        return wea, weather, clothes, sun2, not_suitable
    
    #发送邮件函数
    def send_email(tem,weather,clothes,sun2,hat):
        # 把qq邮箱的服务器地址赋值到变量mailhost上
        email='smtp.qq.com'
        # 实例化一个smtplib模块里的SMTP类的对象
        qqmail = smtplib.SMTP()
        #连接服务器,email是地址,25是SMTP端口号。
        qqmail.connect(email,25)
        #把录入的发件的账号 密码传入登录
        qqmail.login(account,password)
        #邮箱正文
        content= '今天的天气是:'+tem+weather+"\n"+clothes+"\n"+sun2+"\n"+hat
        # 实例化一个MIMEText邮件对象,写入邮件正文,文本格式和编码
        mess= MIMEText(content, 'plain', 'utf-8')
        subject = '今日天气预报'
        # 左边实例化一个Header邮件头对象,该对象需要写入两个参数,
        # 分别是邮件主题和编码,然后赋值给等号左边的变量mess['Subject']。
        mess['Subject'] = Header(subject, 'utf-8')
        try:
            qqmail.sendmail(account, receiver, mess.as_string())
            print ('邮件发送成功')
        except:
            print ('邮件发送失败')
        #退出
        qqmail.quit()
    
    #执行函数
    def work():
        print('开始一次任务')
        #weather_spider()把爬虫参数返回的5个值分别赋值给右边的tem, weather, clothes, sun2, hat
        tem, weather, clothes, sun2, hat = weathers()
        #把获取到的值传进去发送邮箱函数里面
        send_email(tem,weather,clothes,sun2,hat)
        print('任务完成')
    
    #什么时候运行
    worktime=input(str('想要什么时候运行(每天的几点):'))
    schedule.every().day.at(worktime).do(work)
    
    
    
    '''
    schedule是个定时器,在while True死循环中,
    schedule.run_pending()是保持schedule一直运行,
    去查询上面那一堆的任务,在任务中,就可以设置不同的时间去运行。
    '''
    while True:
        schedule.run_pending()
        time.sleep(1)
    
    

    image-20210323143459928

  5. 补充

    • 想要长久运行的最好放服务器里面

    • 这里记录下放服务器踩的坑 巨坑

    • 这个代码直接放服务器里面会报错

    • 这里顺便贴上当时找到的解决办法的博客连接

    • https://blog.csdn.net/mp624183768/article/details/105970608?utm_source=app&app_version=4.5.0

    • 所以放服务器的发送邮件的代码应该是

      def send_email(tem,weather,clothes,sun2,hat):
          smtp=smtplib.SMTP_SSL('smtp.qq.com')
          smtp.ehlo("smtp.qq.com")
          
          smtp.login(account,password)
          content= '今天的天气是:'+tem+weather+"\n"+clothes+"\n"+sun2+"\n"+hat
          message = MIMEText(content, 'plain', 'utf-8')
          subject = '今日天气预报'
          message['Subject'] = Header(subject, 'utf-8')
          try:
              smtp.sendmail(account, receiver, message.as_string())
              print ('邮件发送成功')
          except:
              print ('邮件发送失败')
          smtp.quit()
      
      

      3

      学会了可以发妹子啊

      1

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

longtxue

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

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

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

打赏作者

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

抵扣说明:

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

余额充值