本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理
以下文章來源于青燈編程 ,作者:清風
私信回復“資料”,即可免費領取Python實戰案例講解視頻
Python爬取B站視頻,只需一個B站視頻地址,即可任意下載,觀看地址:
https://www.bilibili.com/video/BV1LX4y1u7VA/
前言
本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,如有問題請及時聯系我們以作處理,
基本開發環境
- Python 3.6
- Pycharm
相關模塊的使用
import jieba import wordcloud import time import requests
目標網頁分析
今天就爬取青燈教育免費公開課的課程評價
網站地址:
https://ke.qq.com/course/384363?taid=10654594091048299&tuin=8aa5eb27
如何獲取課程評價?
打開開發者工具(F12或者滑鼠右鍵點擊檢查),復制評價,在開發者工具當中進行搜索,
這個介面資料有10條評價,一頁評價也是10條評論,所以只需要請求這個鏈接,再通過json資料,字典取值的方式提取評價內容即可,
如何實作多頁爬取
第一頁評價資料介面引數
第二頁評價資料介面引數
通過對比可得:page引數的變化,對應的是頁碼數,構建for回圈即可實作多頁爬取效果,
爬蟲實作代碼
注意點:
headers 引數需要添加 referer 防盜鏈,不然獲取不到資料
import time import requests for page in range(0, 23): time.sleep(1) url = 'https://ke.qq.com/cgi-bin/comment_new/course_comment_list' headers = { 'referer': 'https://ke.qq.com/course/384363?taid=10654585501113707&tuin=8aa5eb27', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' } params = { 'cid': '384363', 'count': '10', 'page': page, 'filter_rating': '0', 'bkn': '1905043087', 'r': '0.30477140651006174', } response = requests.get(url=url, params=params, headers=headers) html_data = response.json() result = html_data['result']['items'] for i in result: comment = i['first_comment'] with open('評價.txt', mode='a', encoding='utf-8') as f: f.write(comment) f.write('\n') print(comment)
詞云實作代碼
import jieba import wordcloud # 讀取檔案內容 f = open(r'D:\python\demo\騰訊課堂評價\評價.txt', encoding='utf-8') txt = f.read() # jieba 分詞 分割詞匯 txt_list = jieba.lcut(txt) string = ' '.join(txt_list) # 詞云圖設定 wc = wordcloud.WordCloud( width=1000, # 圖片的寬 height=700, # 圖片的高 background_color='white', # 圖片背景顏色 font_path='msyh.ttc', # 詞云字體 # mask=py, # 所使用的詞云圖片 scale=15, stopwords={'老師'}, # 停用詞 # contour_width=5, # contour_color='red' # 輪廓顏色 ) # 給詞云輸入文字 wc.generate(string) # 詞云圖保存圖片地址 wc.to_file(r'D:\python\demo\騰訊課堂評價\out.png')
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/239413.html
標籤:Python
