# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from email.mine.text import MIMEText
from email.header import Header
import smtplib#用于发送电子邮件
url='http://www.weather.com.cn/weather/101010100.shtml'
def weather():
#发送请求,无反爬
response=requests.get(url)
#print(response.status_code)
#数据整理,乱码,要设置utf-8
response.encoding='utf-8'
#print(response.text)
bs=BeautifulSoup(response.text,'html.parser')
#print(type(bs))
date=bs.find('h1')
#若有多个h1,则只输出第一个。若要查多个用find_all
wea=bs.find(class_='wea')
#print(wea.text)
tem=bs.find(class_='tem')
#print(tem.text)
return date,wea.text,tem.text
def create_weather():
#获取从网上爬的信息
date,wea,tem=weather()#将元组中的内容给三个变量
#类型是plain纯文本,编码是utf-8
msg=MIMEText('亲爱的,'+date+wea+tem,'plain','utf-8')
#邮件头
msg['Subject']=Header('今天天气','utf-8')
return msg
def send_message():
from_addr=input('发件人邮箱')
pwd=input('输入授权码,非合登录密码')
to_addr=input('收件人')
#邮箱服务商
stmp=smtplib.STMP()
stmp.connect('stmp.qq.com',25)
stmp.login(from_addr,pwd)
content=create_weather()
stmp.sendmail(from_addr,to_addr,content,as_string())#类型转换as_string(),转成string
stmp.quit()
print('sent an email')
if __name__ =='__main__':
send_message()