給女友定時發送睡前小故事

        最近,某可愛要求我忙完之後給她每晚睡前講講小故事,我想了下,網絡上應該有各種資源,小故事也都能搜得到,但是數量比較少,而且格式不夠統一,提取比較困難。轉念一想,面向兒童的睡前故事可能也比較適用,於是我準備從兒童睡前故事中取材,搜索之後發現有一個適合提取睡前故事的網址:

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庫請求訪問

代碼實現:

  1. def getHTMLText(url,headers):
  2. try:
  3. r=requests.get(url,headers=headers,timeout=30)
  4. r.raise_for_status()
  5. r.encoding=r.apparent_encoding
  6. #print(r.text)
  7. return r.text
  8. except:
  9. return "爬取失敗"

簡單地使用BeautifulSoup庫,解析html頁面

找到dl標籤的內容後在查找a標籤中的內容,將提取的鏈接與原網頁頭進行拼接:

  1. def parsehtml(namelist,urllist,html):
  2. url='http://www.tom61.com/'
  3. soup=BeautifulSoup(html,'html.parser')
  4. t=soup.find('dl',attrs={'class':'txt_box'})
  5. #print(t)
  6. i=t.find_all('a')
  7. #print(i)
  8. for link in i:
  9. urllist.append(url+link.get('href'))
  10. namelist.append(link.get('title'))

得到所有網頁鏈接地址之後,訪問該網頁 

查看網頁源代碼

重新對該網頁進行頁面解析,提取出所有p標籤中的內容

由於下面需要使用str類型的字符串,因此用.join方法將text列表用換行符進行分割

  1. def parsehtml2(html):
  2. text=[]
  3. soup=BeautifulSoup(html,'html.parser')
  4. t=soup.find('div',class_='t_news_txt')
  5. for i in t.findAll('p'):
  6. text.append(i.text)
  7. #print(text)
  8. return "\n".join(text)

將爬取的小故事發送到郵箱

  1. def sendemail(url,headers):
  2. msg_from='[email protected]' #發送方郵箱
  3. passwd='' #填入發送方郵箱的授權碼
  4. receivers=[' , '] #收件人郵箱
  5. subject='今日份的睡前小故事' #主題
  6. html=getHTMLText(url,headers)
  7. content=parsehtml2(html) #正文
  8. msg = MIMEText(content)
  9. msg['Subject'] = subject
  10. msg['From'] = msg_from
  11. msg['To'] = ','.join(receivers)
  12. try:
  13. s=smtplib.SMTP_SSL("smtp.qq.com",465) #郵件服務器及端口號
  14. s.login(msg_from, passwd)
  15. s.sendmail(msg_from, msg['To'].split(','), msg.as_string())
  16. print("發送成功")
  17. except:
  18. print("發送失敗")
  19. finally:
  20. s.quit()

簡單地利用smtp協議通過QQmail發送郵件給目標郵箱,端口號爲465,正文內容爲爬取的小故事

實現定時發送功能

在windows的環境中,在cmd中輸入compmgmt.msc,將該腳本文件加入任務計劃程序庫,設置運行時間和頻率

這樣就能實現每晚九點定時發送睡前小故事啦!

 

完整代碼戳:https://github.com/librauee/

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章