最近,某可愛要求我忙完之後給她每晚睡前講講小故事,我想了下,網絡上應該有各種資源,小故事也都能搜得到,但是數量比較少,而且格式不夠統一,提取比較困難。轉念一想,面向兒童的睡前故事可能也比較適用,於是我準備從兒童睡前故事中取材,搜索之後發現有一個適合提取睡前故事的網址:
http://www.tom61.com/ertongwenxue/shuiqiangushi/
一共有700則小故事,嗯,一天一則數量可以滿足,html格式也比較統一,就決定是它了!
查看網頁源代碼,ctrl+F輸入查詢關鍵字幸福王國,定位到相關信息:
發現其故事鏈接包含在dl標籤中的a標籤中的href屬性,
/ertongwenxue/shuiqiangushi/2018-02-25/106432.html,點擊後得到完整網址
http://www.tom61.com/ertongwenxue/shuiqiangushi/2018-02-25/106432.html,接下來要做的就是提取出該鏈接:
模擬瀏覽器訪問網頁,利用requests庫請求訪問
代碼實現:
- def getHTMLText(url,headers):
- try:
- r=requests.get(url,headers=headers,timeout=30)
- r.raise_for_status()
- r.encoding=r.apparent_encoding
- #print(r.text)
- return r.text
-
- except:
- return "爬取失敗"
簡單地使用BeautifulSoup庫,解析html頁面
找到dl標籤的內容後在查找a標籤中的內容,將提取的鏈接與原網頁頭進行拼接:
- def parsehtml(namelist,urllist,html):
- url='http://www.tom61.com/'
- soup=BeautifulSoup(html,'html.parser')
- t=soup.find('dl',attrs={'class':'txt_box'})
- #print(t)
- i=t.find_all('a')
- #print(i)
- for link in i:
- urllist.append(url+link.get('href'))
- namelist.append(link.get('title'))
得到所有網頁鏈接地址之後,訪問該網頁
查看網頁源代碼
重新對該網頁進行頁面解析,提取出所有p標籤中的內容
由於下面需要使用str類型的字符串,因此用.join方法將text列表用換行符進行分割
- def parsehtml2(html):
- text=[]
- soup=BeautifulSoup(html,'html.parser')
- t=soup.find('div',class_='t_news_txt')
- for i in t.findAll('p'):
- text.append(i.text)
- #print(text)
- return "\n".join(text)
將爬取的小故事發送到郵箱
- def sendemail(url,headers):
-
- msg_from='[email protected]' #發送方郵箱
- passwd='' #填入發送方郵箱的授權碼
- receivers=[' , '] #收件人郵箱
-
- subject='今日份的睡前小故事' #主題
- html=getHTMLText(url,headers)
- content=parsehtml2(html) #正文
- msg = MIMEText(content)
- msg['Subject'] = subject
- msg['From'] = msg_from
- msg['To'] = ','.join(receivers)
- try:
- s=smtplib.SMTP_SSL("smtp.qq.com",465) #郵件服務器及端口號
- s.login(msg_from, passwd)
- s.sendmail(msg_from, msg['To'].split(','), msg.as_string())
- print("發送成功")
- except:
- print("發送失敗")
- finally:
- s.quit()
簡單地利用smtp協議通過QQmail發送郵件給目標郵箱,端口號爲465,正文內容爲爬取的小故事
實現定時發送功能
在windows的環境中,在cmd中輸入compmgmt.msc,將該腳本文件加入任務計劃程序庫,設置運行時間和頻率
這樣就能實現每晚九點定時發送睡前小故事啦!
完整代碼戳:https://github.com/librauee/