網(wǎng)易云音樂的評(píng)論里總會(huì)有大批的神評(píng)論,突發(fā)靈感想寫個(gè)爬蟲爬取評(píng)論,后來發(fā)現(xiàn)百度的方法都需要AES加密的密鑰,太麻煩了,本人小白表示看不懂,在知乎上看到網(wǎng)易云有API接口可以直接爬取,不需要任何密鑰。具體代碼如下:
# coding:utf-8
import re
import time
from urllib import request
class PL:
def __init__(self): # 定義初始信息
# 定義http頭信息
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/55.0.2883.87 Safari/537.36",
"referer": "http://music.163.com/song?id=4466775&market=baiduqk"
}
# 使用request打開api接口,獲取數(shù)據(jù)
def single(self, song_id):
offset = 0
comment = []
# 爬蟲爬35*28條評(píng)論
for i in range(28):
# api里limit對(duì)應(yīng)的是每頁多少條,offset對(duì)應(yīng)的是頁數(shù)
single_url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_'+str(song_id)+'?limit35&offset='+str(offset)
offset += 35
# requst訪問api接口獲取數(shù)據(jù)
html_url = request.Request(url=single_url, headers=self.headers)
html = request.urlopen(html_url)
data = html.read()
# 轉(zhuǎn)換獲取數(shù)據(jù)的格式為str
str_data = data.decode()
# 已"content":"為分隔符,分割獲取的字符串
split_data = str_data.split('"content":"')
# 循環(huán)處理所有字符
for i in split_data:
data_split = i.split('","')
if data_split[0] not in comment:
comment.append(data_split[0])
pl = open(r'C:\Users\liushipeng\Documents\pl.txt', 'a+')
# 由于評(píng)論里有些表情字符無法儲(chǔ)存到文本里,刪除所有無法處理的字符,方法比較笨
for i in comment:
try:
pl.write(i + '\n')
except Exception as error:
data = self.error_gbk(error, i)
try:
pl.write(data + '\n')
except Exception as error:
data1 = self.error_gbk(error, data)
try:
pl.write(data1 + '\n')
except Exception as error:
data2 = self.error_gbk(error, data1)
try:
pl.write(data2 + '\n')
except:
pass
time.sleep(2)
pl.close()
# 清除寫入文本里時(shí)報(bào)錯(cuò)的字符
def error_gbk(self, error, content):
u = str(error).split(" '")
u_error = str(u[1]).split("' ")
result = re.sub(u_error[0], '', content)
return result
if __name__ == '__main__':
# 通過歌曲id來訪問歌曲對(duì)應(yīng)的API接口
song_id = '1365221826'
p = PL()
p.single(song_id)
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
