python爬取墨迹天气的8月份的温度情况并发送到邮箱
? ? ? 目標(biāo):獲取墨跡天氣的整個(gè)8月份的溫度情況,并以txt格式的文件發(fā)送到郵箱
? ? ? 環(huán)境:pyhton3.6? ?pycharm軟件? ?163郵箱(163郵箱要打開授權(quán)碼,才能發(fā)送成功)
? ? ? 思路:1.獲取墨跡天氣8月份的溫度網(wǎng)頁源碼
? ? ? ? ? ? ? ? ?2.使用正則表達(dá)式或解析器對(duì)源碼進(jìn)行篩選,得到有用的數(shù)據(jù)信息,本文使用正則表達(dá)式
? ? ? ? ? ? ? ? ?3.將數(shù)據(jù)保存到txt文件
? ? ? ? ? ? ? ? ?4.發(fā)送到郵箱
一、獲取源碼
? ? ? ?獲取墨跡天氣的源碼方法很多,本文使用的requests庫,get()方法獲取源碼,網(wǎng)上有大量的教程,也可參考本人前面寫的文章,此處不展開詳講。代碼附上:
import request from requests.exceptions import RequestException url='https://tianqi.moji.com/weather/china/hubei/jiangxia-district' header = {'User-Agent': 'Mozilla/5.0(Macintosh; Intel Mac OS X 10_11_4)\AppleWebKit/537.36(KHTML, like Gecko) Chrome/52 .0.2743. 116 Safari/537.36'} # 模擬瀏覽器訪問 response = requests.get(url,headers=header) try:if response.status_code==200:return response.text except RequestException:print("請(qǐng)求頁面出錯(cuò)!!!")return None二、篩選數(shù)據(jù)信息
? ? 本文篩選信息使用的是正則表達(dá)式,如何利用正則表達(dá)式篩選信息?首先先觀察一張圖片,注意紅色方框的內(nèi)容。
? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
通過觀察圖片發(fā)現(xiàn)包含日期的代碼:<em>01</em>、<em>02</em>、...其中em是html中的元素,是告訴瀏覽器把其中的文本表示為強(qiáng)調(diào)的內(nèi)容。則正則表達(dá)式為:r'<em>(\d\d)</em>',獲取日期的代碼:
? ? ? ? ? ? ? reg_date =r'<em>(\d\d)</em>' #獲取日期
? ? ? ? ? ? ? reg_num = re.compile(reg_date) #編譯一下,匹配更快
? ? ? ? ? ? ? regdalist = reg_num.findall(html) #全源碼匹配
注意:最后輸出的結(jié)果是以列表的形式輸出
獲取天氣狀況的網(wǎng)頁源碼是:alt="雷陣雨 "></b>? ? ?對(duì)應(yīng)的正則表達(dá)式為 r'alt="(.*?)"></b>'
獲取溫度和風(fēng)的狀況源碼是:<p>26/36°</p>? ?<p>東風(fēng) 3級(jí)</p>? ? ?對(duì)應(yīng)的正則表達(dá)式為: r'<p>(.*?)</p>'
查看全部網(wǎng)頁的源碼的人會(huì)發(fā)現(xiàn),有的地方也有類似<p>.....</p>的代碼,正則表達(dá)式會(huì)否將其篩選出來?答案是:會(huì)的,不過很少,可以從列表中將其刪除掉,留下我們需要的信息。
三、保存為txt文件
如何將數(shù)據(jù)保存在txt文件??
首先打開文件,如果沒有則系統(tǒng)會(huì)自動(dòng)創(chuàng)建,然后將其數(shù)據(jù)寫入進(jìn)去,最后關(guān)閉文件
例: htmlcode= asjgojdopajdsafjbfoso
? ? ? ? pageFile = open('pageCode.txt','w')#以寫的方式打開
? ? ? ? pageCode.txt pageFile.write(htmlcode)#寫入
? ? ? ? ?pageFile.close()#開了記得關(guān)
四、將txt文件發(fā)送到郵箱
如何將附件發(fā)送到郵箱?
第一步選擇發(fā)送方郵件的服務(wù)器和端口號(hào),163郵箱的服務(wù)器對(duì)應(yīng)的端口號(hào)是25,QQ郵箱的服務(wù)器對(duì)應(yīng)的端口號(hào)是465
email_sever = 'smtp.163.com' #使用163郵箱
email_port = '25' #對(duì)應(yīng)的端口號(hào)
第二步可先設(shè)置發(fā)送人和接收人的信息
email = MIMEMultipart() email['From'] = formataddr(["xxxx",email_sender]) (xxxx:發(fā)件人用戶名) email['To'] = formataddr(["xxxx",email_receiver]) (xxxx:收件人用戶名) email['Subject'] = "xxxxxxx" #發(fā)送的主題#正文內(nèi)容 message = "XXXXXX" textApart = MIMEText(message) email.attach(textApart)#附件 txtFile = r'xxxxxxxxx' txtApart = MIMEApplication(open(txtFile, 'rb').read()) txtApart.add_header('Content-Disposition', 'attachment',filename=('gbk','',txtFile)) email.attach(txtApart)第四部發(fā)送郵件
def sendmail(mail_sever,mail_port,mail_sender,mail_pass,mail_receiver):try:mail = smtplib.SMTP(mail_sever,mail_port) #請(qǐng)求郵件服務(wù)器和端口mail.login(mail_sender, mail_pass) #登錄賬號(hào)mail.sendmail(mail_sender, [mail_receiver], email.as_string()) #發(fā)送內(nèi)容mail.quit()print("郵件發(fā)送成功!!!")except:mail.quit()print("郵件發(fā)送失敗!!!")sendmail(email_sever,port,sender,sender_pass,receiver)到此整個(gè)過程就完成。本文僅供參考!!!如有需要改進(jìn)之處,請(qǐng)多多指教,謝謝!!!文末見全碼。
參考資料:
? ? ? ? ??https://www.cnblogs.com/Axi8/p/5757270.html? (參考其保存txt文件)
? ? ? ? ??https://blog.csdn.net/handsomekang/article/details/9811355? ?(參考其發(fā)送帶附件的郵件)
#獲取墨跡天氣中整個(gè)8月份的天氣情況,數(shù)據(jù)保存為txt文件,并發(fā)送到郵箱 #coding utf-8 import requests from requests.exceptions import RequestException import re import smtplib from email.mime.text import MIMEText from email.utils import formataddr from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication#獲取數(shù)據(jù)部分 def get_html(url):header = {'User-Agent': 'Mozilla/5.0(Macintosh; Intel Mac OS X 10_11_4)\AppleWebKit/537.36(KHTML, like Gecko) Chrome/52 .0.2743. 116 Safari/537.36'} # 模擬瀏覽器訪問response = requests.get(url,headers=header) #請(qǐng)求訪問鏈接try:if response.status_code==200: #如果請(qǐng)求狀態(tài)正常,則返回源碼return response.textexcept RequestException: #拋出異常信息print("請(qǐng)求頁面出錯(cuò)!!!")return Nonedef html_Select(html):num=0num_o=0reg_date =r'<em>(\d\d)</em>' #獲取日期reg_st = r'alt="(.*?)"></b>' #獲取天氣狀況reg_team = r'<p>(.*?)</p>'reg_num = re.compile(reg_date) #編譯一下,匹配更快reg_wea = re.compile(reg_st)reg_temp = re.compile(reg_team)regdalist = reg_num.findall(html) #全源碼匹配regstlist = reg_wea.findall(html)regtelist = reg_temp.findall(html)del regdalist[0]del regtelist[62]#print(regdalist)#print(regstlist)#print(regtelist)temp_File = open('8月份溫度.txt', 'w')while num<32:for data in regdalist[num:num+1]:temp_File.write(data)for weather in regstlist[num:num+1]:temp_File.write(weather)for temp in regtelist[num_o:num_o+2]:temp_File.write(temp + "\n")#temp_File.write("=================================")num += 1num_o +=2temp_File.close()#發(fā)送郵件部分 #設(shè)置發(fā)送郵件的服務(wù)器和端口 email_sever = 'smtp.163.com' #使用163郵箱 email_port = '25' #對(duì)應(yīng)的端口號(hào)#設(shè)置發(fā)件人和收件人 email_sender = 'xxxxxxx@163.com' email_pass = 'xxxxxxxx' #此處是授權(quán)密碼 email_receiver = 'xxxxxxx@qq.com'#設(shè)置發(fā)送內(nèi)容以及主題 email = MIMEMultipart() email['From'] = formataddr(["xxxxx",email_sender]) email['To'] = formataddr(["xxxxxxxx",email_receiver]) email['Subject'] = "xxxxxxxxx"#正文內(nèi)容 message = "xxxxxxxxxxx" textApart = MIMEText(message) email.attach(textApart)#附件 txtFile = r'xxxxxxxxxxxx' txtApart = MIMEApplication(open(txtFile, 'rb').read()) txtApart.add_header('Content-Disposition', 'attachment',filename=('gbk','',txtFile)) email.attach(txtApart)#發(fā)送郵件 def send_email(mail_sever,mail_port,mail_sender,mail_pass,mail_reciver):try:mail = smtplib.SMTP(mail_sever,mail_port)mail.login(mail_sender,mail_pass)mail.sendmail(mail_sender,[mail_reciver],email.as_string())mail.quit()print("郵件發(fā)送成功!!!")except:mail.quit()print("郵件發(fā)送失敗!!!")if __name__ == '__main__':url='https://tianqi.moji.com/weather/china/hubei/jiangxia-district'html=get_html(url)html_Select(html)send_email(email_sever,email_port,email_sender,email_pass,email_receiver)?
總結(jié)
以上是生活随笔為你收集整理的python爬取墨迹天气的8月份的温度情况并发送到邮箱的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 组件封装 - 省市区联动组件
- 下一篇: 【数据科学】使用Python建立你的数据