手把手教你使用Python抓取QQ音樂數據(第三彈)

【一、項目目標】

通過手把手教你使用Python抓取QQ音樂數據(第一彈)我們實現了獲取 QQ 音樂指定歌手單曲排行指定頁數的歌曲的歌名、專輯名、播放鏈接。

通過手把手教你使用Python抓取QQ音樂數據(第二彈)我們實現了獲取 QQ 音樂指定歌曲的歌詞和指定歌曲首頁熱評。

此次我們在項目(二)的基礎上獲取更多評論並生成詞雲圖,形成手把手教你使用Python抓取QQ音樂數據(第三彈)。

【二、需要的庫】

主要涉及的庫有:requests、json、wordcloud、jieba

如需更換詞雲圖背景圖片還需要numpy庫和PIL庫(pipinstall pillow)

【三、項目實現】

1、首先回顧一下,下面是項目(二)獲取指定歌曲首頁熱評的代碼;

<code> def get_comment(i): url_3 = 'https://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg' headers = { 'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', # 標記了請求從什麼設備,什麼瀏覽器上發出 } params = {'g_tk_new_20200303': '5381', 'g_tk': '5381', 'loginUin': '0', 'hostUin': '0', 'format': 'json', 'inCharset': 'utf8', 'outCharset': 'GB2312', 'notice': '0', 'platform': 'yqq.json', 'needNewCode': '0', 'cid': '205360772', 'reqtype': '2', 'biztype': '1', 'topid': id, 'cmd': '8', 'needmusiccrit': '0', 'pagenum': '0', 'pagesize': '25', 'lasthotcommentid': '', 'domain': 'qq.com', 'ct': '24', 'cv': '10101010'} res_music = requests.get(url_3,headers=headers,params=params) # 發起請求 js_2 = res_music.json() comments = js_2['hot_comment']['commentlist'] f2 = open(i+'評論.txt','a',encoding='utf-8') #存儲到txt中 for i in comments: comment = i['rootcommentcontent'] + '\n——————————————————————————————————\n' f2.writelines(comment) # print(comment) f2.close() /<code>

2、下面來考慮如何獲取後面的評論,下圖是項目(二)評論頁面的parms參數;

image

3、網頁無法選擇評論的頁碼,想看後面的評論智能一次一次的點擊“點擊加載更多”;我們可以點擊一下看看parms有什麼變化。

image

4、這裡有個小技巧,先點擊下圖所示clear按鈕,把network界面清空,再點擊“點擊加載更多”,就能直接找到第二頁的數據。

image

image

5、點擊加載更多後出現下圖。

image

image

6、發現不止pagenum變了,cmd和pagesize也變了,到底那個參數的問題呢,那我們再看下第三頁;

image

7、只有pagenum變了,那我們嘗試一下把pagenum改成“0”,其他不變,能正常顯示第一頁數據嗎?

image

第一頁第一條評論

image

第一頁最後一條評論

image

8、能正常顯示,那就確定思路了:用第二頁的parms,寫一個for循環賦值給pagenum,參考項目(二)把評論抓取到txt。

9、代碼實現:為了不給服務器造成太大壓力,我們本次只爬取20頁數據。

<code>import requests,json def get_id(i): global id url_1 = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp' # 這是請求歌曲評論的url headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'} params = {'ct': '24', 'qqmusic_ver': '1298', 'new_json': '1', 'remoteplace': 'txt.yqq.song', 'searchid': '71600317520820180', 't': '0', 'aggr': '1', 'cr': '1', 'catZhida': '1', 'lossless': '0', 'flag_qc': '0', 'p': '1', 'n': '10', 'w': i, 'g_tk': '5381', 'loginUin': '0', 'hostUin': '0', 'format': 'json', 'inCharset': 'utf8', 'outCharset': 'utf-8', 'notice': '0', 'platform': 'yqq.json', 'needNewCode': '0'} res_music = requests.get(url_1,headers=headers,params=params) json_music = res_music.json() id = json_music['data']['song']['list'][0]['id'] return id # print(id) /<code>

<code>def get_comment(i): url_3 = 'https://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg' headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'} f2 = open(i+'評論.txt','a',encoding='utf-8') #存儲到txt中 for n in range(20): params = {'g_tk_new_20200303': '5381', 'g_tk': '5381', 'loginUin': '0', 'hostUin': '0', 'format': 'json', 'inCharset': 'utf8', 'outCharset': 'GB2312', 'notice': '0', 'platform': 'yqq.json', 'needNewCode': '0', 'cid': '205360772', 'reqtype': '2', 'biztype': '1', 'topid': '247347346', 'cmd': '6', 'needmusiccrit': '0', 'pagenum':n, 'pagesize': '15', 'lasthotcommentid': 'song_247347346_3297354203_1576305589', 'domain': 'qq.com', 'ct': '24', 'cv': '10101010'} res_music = requests.get(url_3,headers=headers,params=params) js_2 = res_music.json() comments = js_2['comment']['commentlist'] for i in comments: comment = i['rootcommentcontent'] + '\n——————————————————————————————————\n' f2.writelines(comment) # print(comment) f2.close() input('下載成功,按回車鍵退出!') /<code>

<code>def main(i): get_id(i) get_comment(i) main(i = input('請輸入需要查詢歌詞的歌曲名稱:')) /<code>

10、詞雲圖代碼

<code>from wordcloud import WordCloud import jieba import numpy import PIL.Image as Image #以上兩個庫是為了更換詞雲圖背景圖片 def cut(text): wordlist_jieba=jieba.cut(text) space_wordlist=" ".join(wordlist_jieba) return space_wordlist with open("句號評論.txt" ,encoding="utf-8")as file: text=file.read() text=cut(text) mask_pic=numpy.array(Image.open("心.png")) wordcloud = WordCloud(font_path="C:/Windows/Fonts/simfang.ttf", collocations=False, max_words= 100, min_font_size=10, max_font_size=500, mask=mask_pic).generate(text) image=wordcloud.to_image() # image.show() wordcloud.to_file('雲詞圖.png') # 把詞雲保存下來 /<code>

11、成果展示

image

image

【四、總結】

1、項目三比項目二多的功能:一是通過尋找parms參數裡每一頁評論頁碼之間的關係,爬取更多的評論;二是學會生成詞雲圖;(注意讀取文件的路徑)

2、WordCloud更多參數詳見下圖,可以研究出更多的玩法;

image

3、不只.txt可以作為詞雲圖的數據源,csv、Excel也可以:

<code>import xlrd #引入excel讀取模塊 datafile_path = '你的Excel文件.xlsx' data = xlrd.open_workbook(datafile_path) #文件名以及路徑 table = data.sheet_by_name('sheet') ##通過名稱獲取Sheet1表格 nrows = table.nrows #獲取該Sheet1中的有效行數 list = [] for i in range(nrows): value = str(table.row_values(i)[1]) # print(value) list.append(value) # print(pingjia_list) text = str(list).replace("'", '').replace(',', '').rstrip(']').lstrip('[') # print(text) /<code>

4、爬QQ音樂項目到此告一段落,如有需要的話可以通過Scrapy框架爬取更多的歌曲信息、歌詞、評論。但是作為練手項目,重要的不是爬多少數據,而是學會如何爬取指定的數據。

5、第四彈小編將會把前面三個項目封裝在一起,通過菜單控制爬取不同數據,敬請期待。

6、需要本文源碼的話,請在後臺回覆“QQ音樂”四個字進行獲取。