----------------------------------------------------------- 学无止境 ------------------------------------------------------
前言: 大家好, 欢迎来到誉雪飞舞的博客园, 我的每篇文章都是自己用心编写,
算不上精心但是足够用心分享我的自学知识, 希望大家能够指正我, 互相学习成长.
转载请注明: https://www.cnblogs.com/wyl-pi/p/10635476.html
墨迹天气, 不是老年人大都耳熟能详吧, 用着呢吧或者或用过吧, 嗯... 的确不错.
(过一阵子再给大家更新一个带语音播报的电子邮箱之类的东西出来, 分享给大家, 敬请期待吧.)
会运行错误, 得先安装库 sudo pip install SMTP or sudo apt-get SMTP
尴尬我也忘了.....
先上一个百度的非常实用简单易懂的小实例, 作为下文的学习基石.
- #!/usr/bin/python
- # -*- coding: UTF-8 -*-
- import smtplib
- from email.mime.text import MIMEText
- from email.header import Header
- # 第三方 SMTP 服务
- mail_host="smtp.sohu.com" #设置服务器
- mail_user="wyl1346****525@sohu.com" #用户名
- mail_pass="** 密码 - password**" #口令
- sender = 'wyl1346*****25@sohu.com'
- ## 搜狐向 QQ 发送邮件
- receivers = ['1346*****25@qq.com'] # 接收邮件, 可设置为你的 QQ 邮箱或者其他邮箱
- ## 邮件的来去地址
- message = MIMEText('Here is email_text.Python 邮件发送测试...', 'plain', 'utf-8')
- message['From'] = Header(sender, 'utf-8')
- message['To'] = Header(receivers[0], 'utf-8')
- ## 邮件内容 经过 Header 函数编译成 utf-8 格式的邮件 ##
- subject = 'Python SMTP 邮件测试'
- message['Subject'] = Header(subject, 'utf-8')
- try:
- SmtpObj = smtplib.SMTP() # 创建 SMTP 对象
- print("SMTP complete")
- SmtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
- print("connect complete") # mail_host 服务器 地址
- SmtpObj.login(mail_user,mail_pass)
- print("login complete")
- ## SMTP.sendmail(from_addr, to_addrs, msg) ##
- ## from 发送者地址 to 接受者地址 msg 发送的内容
- SmtpObj.sendmail(sender, receivers, message.as_string())
- print("邮件发送成功")
- except smtplib.SMTPException:
- print("Error: 无法发送邮件")
以后有我这个文章你手机可以删掉某 App, 缓解内存压力了. 而且每天通过邮件查看天气非常个性,
高大上说不上起码是不走寻常路的奇葩, 哈哈, 没错我就是这样.
毕竟好钻研不是坏事, 不要总是拿一些唾手可得的东西, 没啥意思, 没有技术含量, 自己动手, 嗯, 是吧! 那感觉就是不一样.
好, 上面的小实例看懂后, 后面也好办, no problem.
- import time
- import smtplib
- import requests
- import random
- import socket
- import bs4
- from bs4 import BeautifulSoup
- from email.mime.text import MIMEText
- from email.header import Header
- def get_content(url):
- header = {
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
- 'Accept-Encoding' : 'gzip, deflate',
- 'Accept-Language' : 'zh-CN,zh;q=0.9,en;q=0.8',
- 'Cache-Control' : 'max-age=0',
- 'Connection' : 'keep-alive',
- 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
- }
- timeout = random.choice(range(80, 180))
- while True:
- try:
- rep = requests.get(url,headers = header,timeout = timeout)
- rep.encoding = 'utf-8'
- break
- except socket.timeout as e:
- print( '3:', e)
- time.sleep(random.choice(range(8,15)))
- except socket.error as e:
- print( '4:', e)
- time.sleep(random.choice(range(20, 60)))
- return rep.text
- def get_weather(url,data):
- air_list = []
- weather_list = []
- #weather_status = []
- soup = BeautifulSoup(data,'lxml')
- div = soup.find('div',{'class' : 'forecast clearfix'})
- air_quality = div.find('strong',class_='level_2').string #空气质量
- date = div.find('a',href='https://tianqi.moji.com/today/china/shandong/penglai').string
- wind_direction = div.find('em').string #风向
- wind_grade = div.find('b').string #风速
- ul = div.find('ul',{'class' : 'clearfix'})
- ## 天气情况抽取 ##
- a = []
- li = ul.find_all('li')
- j=0
- #return li
- for i in li:
- j+=1
- if j==2:
- a = i
- a = str(a).replace('\n','').replace('\t','').replace('','').replace("</li>","").replace('\r','')
- a = a.replace('<li><span>','').replace('<imgalt=','').replace('src="https://h5tq.moji.com/tianqi/assets/images/weather/','')
- a = a.replace('.png/></span>','').replace('.png"/></span>','').replace('"','').replace('\t','')
- for x in range(100,0,-1):
- #print("w{0}".format(x))
- a = a.replace(("w{0}".format(x)),'')
- if(len(a)==2):
- a = a[0:1]
- if(len(a)==4):
- a = a[0:2]
- for day in li:
- if not isinstance(day,bs4.element.Tag):
- date = day.find('a',href='https://tianqi.moji.com/today/china/shandong/penglai').string
- weather_list.append(day.string)
- if not isinstance(day,bs4.element.Tag):
- wind_direction = day.find('em').string
- wind_grade = day.find('b').string
- Tempreture = weather_list[2]
- air_quality =air_quality.replace("\n","").replace(' ','')
- #air_quality = str(air_quality).replace('\n','').replace(' ','')
- #print("'data' {0} 'Tempreture' {1},air_quality {2}\n,'wind_grade' {3},'wind_direction' {4}".format(date,Tempreture,air_quality,wind_grade,wind_direction))
- return ("时 间 : {}\n 天气情况: {}\n 温 度 : {}\n 风 向 : {}\n 风 速 : {}\n 空气质量: {}\n".format(date,a,Tempreture,wind_direction,wind_grade,air_quality))
- def send_email(email):
- ''' sender = input('From: ')
- password = input('password:')
- smtp_server = input('SMTP_Server:')
- '''
- ## FROM ##
- sender = 'wyl1346788525@sohu.com'
- sent_host = 'smtp.sohu.com'
- sent_user = 'wyl1346788525@sohu.com'
- sent_pass = 'cxlgWYL1'
- ## TO ##
- receivers = ['24******09@qq.com'] 99
- #message = MIMEText("亲爱的, 我现在来播报今天的蓬莱天气.\n(嗯... 其实现在还只能看不能播) 如下所示:\n 时 间 | 天气情况 | 温 度 | 风 向 | 风 速 | 空气质量 \ n'{0}\n".format(result),'plain','utf-8')
- message = MIMEText("亲爱的今天蓬莱天气是这样的呦 :\n{}\n".format(result),'plain','utf-8')
- ## JUST USE TO DISPLAY ##
- message['From'] = Header('自定义 From','utf-8')
- message['To'] = Header('自定义 To','utf-8')
- Subject = "今天的天气预报详情!"
- message['Subject'] = Header(Subject,'utf-8') #标题
- try:
- server = smtplib.SMTP()
- #server = smtplib.SMTP(sent_host,25)
- print("SMTP complete")
- server.connect(sent_host,25)
- print("connect complete")
- #server.set_debuglevel(1)
- server.login(sent_user,sent_pass)
- print("login complete")
- server.sendmail(sender,receivers[0],message.as_string())
- print("邮件发送成功")
- #server.quit()
- except smtplib.SMTPException:
- print("Error: 发生未知错误, 无法发送邮件!")
- if __name__ == '__main__':
- result =[]
- url = 'http://tianqi.moji.com/weather/china/shandong/penglai'
- data = get_content(url)
- result = get_weather(url,data)
- result = str(result).replace("\\r","").replace('\t','').replace('\r','').replace("\\n","")
- print("result is \n{}\n".format(result))
- send_email(result)
嗯中间有很多小 BUG 我都修复了, 但是这个运行结果还是有问题, 细心的朋友应该发现了, 看到了吧, 天气情况: 晴 w
我们先找到天气情况的变量名为 a, 所以找到对于变量 a 的编辑的地方查询问题.
先 print(a) 看为什么 天气情况 剪裁后的信息, 输出变量 a 为:"晴 w0 晴", 哦..... 经过我的查询, 发现是因为 for x in range(100,1,-1) 的原因
(这张截图是我改动之后的) 它只遍历到 w1, 没有到 w0,,, 粗心了, 很多朋友可能会问我为什么加这些多此一举的 for 直接去掉 w0 不就行了, 我第一天也是这么想的,
然而第二天它就变成了 w3,w1,w10,,,,, 所以我就简单粗暴的直接 for 遍历; 后面的 len 函数是因为每天的天气状况不同比如 "小雨","晴","阴" 字数上有不同我通
过 len 函数进行处理截取我想要留下的内容, 呈现给用户;(因为初期 bug 挺多的, 而且使用 BeautifulSoup 库里有个挺废头的问题, 过了挺久了, 忘了, 反正差不多是类
型的问题, 网上能百度出来很多, 但是出问题的解析答案寥寥无几, 几乎没有, 也只能 FQ 出去还有不少, 但英语硬伤的, 翻译很多原意就曲解了, 致使本来就懵, 看完之后可想而知的状态.......)
我后来呢是另辟新径找到了别的解决方法, 所以没有继续太过纠结这个问题, 我推荐大家还是耐住性子钻研下去, 的确成长, 不过也要把握个度 (我是因为要比赛赶进度
时间不多, 不允许我钻下去), 不要非得不撞南墙不回头, 不整出来誓不罢休, 精神可嘉但效果欠佳.
- Tag
- NavigableString
- BeautifulSoup
- Comment
如有网友大佬有推荐切实可行的优化方法, 我一定洗耳恭听, 我在这提前谢谢您了.
修复好 bug 运行检测:
检验邮箱结果:
过一阵子再给大家更新一个带语音播报的邮件出来? 我也不知道没想好, 会分享给大家, 敬请期待吧.
当然这篇教程只是用来学习, 请勿进行商业活动甚至非法活动, 切勿侵害他人权益, 提前声明概不负责.
如果觉得我的文章还不错, 关注一下, 顶一下 , 我将会用心去创作更好的文章, 敬请期待.
来源: https://www.cnblogs.com/wyl-pi/p/10635476.html