Python定时发送天气预报邮件代码实例

yipeiwu_com6年前Python基础

这篇文章主要介绍了Python定时发送天气预报邮件代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

用python爬虫爬到的天气预报,使用smtplib和email模块可以发送到邮箱,使用schedule模块可以定时发送。以下是代码~

#导入模块
import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import schedule
import time

#输入邮箱发件人、收件人以及邮箱的授权码
account = str(input('请输入发件人邮箱地址:'))
password = str(input('请输入邮箱授权码:'))
receiver = str(input('请输入收件人邮箱地址:'))

#建立天气网爬虫,爬取天气信息
def weather_spider():
  #模拟浏览器:
  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/weather/101211001.shtml'
  #数据获取:
  res=requests.get(url,headers=headers)
  res.encoding='utf-8'
  #数据解析:
  soup=BeautifulSoup(res.text,'html.parser')
  #数据提取:
  tem1= soup.find(class_='tem')
  weather1= soup.find(class_='wea')
  tem=tem1.text
  weather=weather1.text
  return tem,weather

#发送邮件的代码
def send_email(tem,weather):
  global account,password,receiver
  mailhost='smtp.qq.com'
  qqmail = smtplib.SMTP()
  qqmail.connect(mailhost,25)
  qqmail.login(account,password)
  content= '衢州的天气是:\n'+tem+weather
  message = MIMEText(content, 'plain', 'utf-8')
  subject = '今日天气预报from python'
  message['Subject'] = Header(subject, 'utf-8')
  try:
    qqmail.sendmail(account, receiver, message.as_string())
    print ('邮件发送成功')
  except:
    print ('邮件发送失败')
  qqmail.quit()

#建立任务
def job():
  print('开始一次任务')
  tem,weather = weather_spider()
  send_email(tem,weather)
  print('任务完成')

#定时发送
schedule.every().day.at("7:00").do(job) 
while True:
  schedule.run_pending()
  time.sleep(1)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现的几个常用排序算法实例

前段时间为准备百度面试恶补的东西,虽然最后还是被刷了,还是把那几天的“战利品”放点上来,算法一直是自己比较薄弱的地方,以后还要更加努力啊。 下面用Python实现了几个常用的排序,如快速...

python matlibplot绘制3D图形

python matlibplot绘制3D图形

本文实例为大家分享了python matlibplot绘制3D图形的具体代码,供大家参考,具体内容如下 1、散点图使用scatter from mpl_toolkits.mplot3...

Python下的Softmax回归函数的实现方法(推荐)

Python下的Softmax回归函数的实现方法(推荐)

Softmax回归函数是用于将分类结果归一化。但它不同于一般的按照比例归一化的方法,它通过对数变换来进行归一化,这样实现了较大的值在归一化过程中收益更多的情况。 Softmax公式 S...

简单谈谈python基本数据类型

int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647 在64位系统上,整数的位数为64位,取值范围为...

Python如何实现MySQL实例初始化详解

前言 相信每位程序员对mysql应该都不陌生,MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品。我们在日常开发中少不了要接触mys...