[python应用案例] 一.BeautifulSoup爬取天气信息并发送至QQ邮箱
前面作者寫(xiě)了很多Python系列文章,包括:
- Python基礎(chǔ)知識(shí)系列:Python基礎(chǔ)知識(shí)學(xué)習(xí)與提升
- Python網(wǎng)絡(luò)爬蟲(chóng)系列:Python爬蟲(chóng)之Selenium+Phantomjs+CasperJS
- Python數(shù)據(jù)分析系列:知識(shí)圖譜、web數(shù)據(jù)挖掘及NLP
??
接下來(lái)作者將學(xué)習(xí)并講解一些Python小應(yīng)用,它將結(jié)合Python爬蟲(chóng)、數(shù)據(jù)分析、web開(kāi)發(fā)或其他功能進(jìn)行介紹。一方面希望能提升讀者的Python學(xué)習(xí)興趣,另一方面也希望讀者能學(xué)到些知識(shí),做些好玩的應(yīng)用。本篇文章主要講解BeautifulSoup爬取每日天氣信息,然后將信息發(fā)送至QQ郵箱,其難點(diǎn)是如何配置QQ郵箱發(fā)送Python郵件。基礎(chǔ)性應(yīng)用文章,希望對(duì)您有所幫助,如果文章中出現(xiàn)錯(cuò)誤或不足之處,還請(qǐng)海涵~
一. BeautifulSoup爬取天氣信息
1.分析網(wǎng)頁(yè)
中國(guó)天氣網(wǎng):?http://www.weather.com.cn/weather/101260101.shtml
我們需要爬取貴陽(yáng)市當(dāng)天的天氣信息,比如“5月3日 陣雨 18/15℃”
接下來(lái)通過(guò)瀏覽器審查元素,可以看到這些信息位于<li class="sky skyid lv3 on">元素下,接著我定義class為“wea”和“tem”的元素進(jìn)行定位,核心代碼為:
name = soup.find_all(attrs={"class":"sky skyid lv3 on"})
2.完整代碼
# -*- coding: UTF-8 -*- import urllib import urllib.request from bs4 import BeautifulSoup#下載數(shù)據(jù) url = "http://www.weather.com.cn/weather/101260101.shtml" content = urllib.request.urlopen(url).read() soup = BeautifulSoup(content,"html.parser") #print(soup.title.get_text())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 + " 溫度:" + temcontent = content.replace("\n","")print(content)輸出結(jié)果如下圖所示:
二. QQ郵箱設(shè)置STMP
在使用Python自動(dòng)發(fā)送郵件之前,需要對(duì)我們的QQ郵箱進(jìn)行簡(jiǎn)單的配置,過(guò)程如下:
1.首先登陸QQ郵箱,選擇“賬戶”如下圖所示:
2.在賬戶頁(yè)面往下拉,看到“POP3/SMTP”設(shè)置,點(diǎn)擊開(kāi)啟按鈕,如下圖所示:
3.彈出如下圖所示界面,然后發(fā)送這條短信至指定號(hào)碼,點(diǎn)擊“我已發(fā)送”按鈕。
4.彈出的提示中會(huì)顯示16位授權(quán)碼,注意一定要記住這個(gè)授權(quán)碼,后面寫(xiě)Python代碼也需要,然后點(diǎn)擊“確定”按鈕。
5.接下來(lái)將收取選項(xiàng)設(shè)置為“全部”,并點(diǎn)擊“保存”按鈕即可。注意端口號(hào)如下:
三. Python自動(dòng)發(fā)送郵件
Python 的 email 模塊里包含了許多實(shí)用的郵件格式設(shè)置函數(shù),可以用來(lái)創(chuàng)建郵件“包裹”。使用的 MIMEText 對(duì)象,為底層的 MIME(Multipurpose Internet MailExtensions,多用途互聯(lián)網(wǎng)郵件擴(kuò)展類型)協(xié)議傳輸創(chuàng)建了一封空郵件,最后通過(guò)高層的SMTP 協(xié)議發(fā)送出去。 MIMEText 對(duì)象 msg 包括收發(fā)郵箱地址、郵件正文和主題,Python 通過(guò)它就可以創(chuàng)建一封格式正確的郵件。smtplib 模塊用來(lái)設(shè)置服務(wù)器連接的相關(guān)信息。
Python SMTP 對(duì)象使用 sendmail 方法發(fā)送郵件,語(yǔ)法如下:(參考: Python SMTP發(fā)送郵件)
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])參數(shù)說(shuō)明:
- from_addr: 郵件發(fā)送者地址。
- to_addrs: 字符串列表,郵件發(fā)送地址。
- msg: 發(fā)送消息
這里要注意一下第三個(gè)參數(shù),msg 是字符串,表示郵件。我們知道郵件一般由標(biāo)題,發(fā)信人,收件人,郵件內(nèi)容,附件等構(gòu)成,發(fā)送郵件的時(shí)候,要注意 msg 的格式。這個(gè)格式就是 smtp 協(xié)議中定義的格式。
代碼如下: # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.header import Header#發(fā)送郵件 msg_from = "1455136241@qq.com" #授權(quán)碼(而不是密碼) EMAIL_HOST_PASSWORD = '****htacisgv****' #接受郵件 msg_to = "15201615157@163.com" #主題 subject = "Python測(cè)試代碼" #正文 content = "女神,這是我使用python smtplib及email模塊發(fā)送的郵件。" print(content)#MIMEText構(gòu)建對(duì)象 參數(shù)分別是:郵件正文、MIMEsubtype中'plain'表示純文本、utf-8編碼 msg = MIMEText(content, 'plain', 'utf-8') msg['Subject'] = subject msg['From'] = msg_from msg['To'] = msg_to#郵件服務(wù)器及端口號(hào) #smtplib.SMTPServerDisconnected: Connection unexpectedly closed try:s = smtplib.SMTP_SSL("smtp.qq.com",465) #端口號(hào)s.set_debuglevel(1)s.login(msg_from, EMAIL_HOST_PASSWORD)s.sendmail(msg_from, msg_to, msg.as_string())print("發(fā)送成功") except s.SMTPException.e:print("發(fā)送失敗")print(e) finally:s.quit()
發(fā)送成功之后如下圖所示,注意login()輸入郵箱名和授權(quán)碼,而不是密碼。
運(yùn)行過(guò)程輸出內(nèi)容如下:
>>> 女神,這是我使用python smtplib及email模塊發(fā)送的郵件。 send: 'ehlo [192.168.0.101]\r\n' reply: b'250-smtp.qq.com\r\n' reply: b'250-PIPELINING\r\n' reply: retcode (250); Msg: b'smtp.qq.com\nPIPELINING\' send: 'AUTH PLAIN ADE0NTUxMzYyNDFAcXEuY29tAGVveXFodGFjaXNndmlmYmg=\r\n' reply: b'235 Authentication successful\r\n' reply: retcode (235); Msg: b'Authentication successful' send: 'mail FROM:<1455136241@qq.com> size=296\r\n' reply: b'250 Ok\r\n' reply: retcode (250); Msg: b'Ok' send: 'rcpt TO:<15201615157@163.com>\r\n' reply: b'250 Ok\r\n' reply: retcode (250); Msg: b'Ok' send: 'data\r\n' reply: b'354 End data with <CR><LF>.<CR><LF>\r\n' reply: retcode (354); Msg: b'End data with <CR><LF>.<CR><LF>' data: (354, b'End data with <CR><LF>.<CR><LF>') send: b'Content-Type: text/plain; charset="utf-8"\r\nMIME-Version: 1.0\r\n...r\nTo: 15201615157@163.com\r\n' reply: b'250 Ok: queued as \r\n' reply: retcode (250); Msg: b'Ok: queued as' data: (250, b'Ok: queued as') 發(fā)送成功 send: 'quit\r\n' reply: b'221 Bye\r\n' reply: retcode (221); Msg: b'Bye' >>>四. 完整代碼實(shí)現(xiàn)
完整代碼如下所示:
# -*- coding: UTF-8 -*- import urllib import urllib.request from bs4 import BeautifulSoup#下載數(shù)據(jù) url = "http://www.weather.com.cn/weather/101260101.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 + " 溫度:" + temcontent = content.replace("\n","")print(content)#發(fā)送郵件 import smtplib from email.mime.text import MIMEText from email.header import Headermsg_from = "1455136241@qq.com" EMAIL_HOST_PASSWORD = '****htacisgv****' msg_to = "15201615157@163.com" subject = "Python爬取天氣" other = content + "\n這是我使用python smtplib及email模塊發(fā)送的郵件。" print(other)msg = MIMEText(other,'plain','utf-8') msg['Subject'] = subject msg['From'] = msg_from msg['To'] = msg_totry: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("發(fā)送成功") except s.SMTPException.e:print("發(fā)送失敗")print(e) finally:s.quit()發(fā)送成功之后如下圖所示:
需要注意,代碼有時(shí)能發(fā)送成功,有時(shí)報(bào)錯(cuò)“smtplib.SMTPServerDisconnected: Connection unexpectedly closed”,網(wǎng)上說(shuō)是設(shè)置端口465的原因,但作者已經(jīng)設(shè)置了的,不知道為什么?希望博友幫忙。
?(By:Eastmount 2018-5-3 下午4點(diǎn) ??http://blog.csdn.net/eastmount/)總結(jié)
以上是生活随笔為你收集整理的[python应用案例] 一.BeautifulSoup爬取天气信息并发送至QQ邮箱的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [python爬虫] selenium爬
- 下一篇: 【python数据挖掘课程】二十三.时间