"""
BeautifulSoup爬取天气信息并发送至QQ邮箱
"""
import smtplib
import urllib.request
from bs4 import BeautifulSoup
from email.mime.text import MIMEText
url = "http://www.weather.com.cn/weather/101040100.shtml"
content = urllib.request.urlopen(url).read()
soup = BeautifulSoup(content, "html.parser")
content = ""
name = soup.find_all(attrs={"class": "sky skyid lv3 on"})
for u in name:
wea = u.find(attrs={"class": "wea"}).get_text()
tem = u.find(attrs={"class": "tem"}).get_text()
content = "天气:" + wea + " 温度:" + tem
content = content.replace("\n", "")
print(content)
msg_from = "962565593@qq.com"
EMAIL_HOST_PASSWORD = 'hemdjqjmvcqjbfbc'
msg_to = "1933762162@qq.com"
subject = "重庆天气预报"
other = content + "\n媳妇儿,照顾好自己哦!!!"
print(other)
msg = MIMEText(other, 'plain', 'utf-8')
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = msg_to
try:
s = smtplib.SMTP_SSL("smtp.qq.com", 465)
s.set_debuglevel(1)
s.login(msg_from, EMAIL_HOST_PASSWORD)
s.sendmail(msg_from, msg_to, msg.as_string())
print("发送成功")
except Exception as e:
print("发送失败")
print(e)
finally:
s.quit()