简单的网易云音乐热门评论爬虫

简单的网易云音乐热门评论爬虫

注:本文没有什么技术含量,就是一个普通的AJAX数据爬虫,适合新手练习

目标:爬取网易云音乐歌曲的热门评论

分析:本次爬虫不难,思路是请求和获取数据,网易云音乐的评论是通过AJAX的方式进行加载的,打开chrome进行分析就很容易分析出来,唯一难点是它的传送数据是加密的,如果不知道加密的方法的话,就无法构造请求。

https://music.163.com/weapi/event/user/permission?csrf_token=

这个就是用浏览器打开网易云音乐时,浏览器调用的API,这个API是要用到加密算法的,后面经过搜索,发现了一个更为简单的API

https://music.163.com/api/v1/resource/comments/R_SO_4_<song_id>

这个API的请求不需要进行加密,可以直接获取得到歌曲的评论,虽然返回的不是所有评论,但是这次的目标是获取歌曲的热门评论,返回的数据中包含有热门评论,可以实现我们的目标,足够了。

思路:思路和普通的爬虫思路一样,发送请求,获取数据,分析数据,存取数据

环境:python3.6.3,MongoDB4.0.0

模块:request,json,pymongo,time,re

代码:

# -*-coding:utf-8-*-
# Author: AnswerW3I
# version:3.6.3
import requests
import json
import time
import pymongo
import re

class Spider(object):
    def __init__(self, song):
        self.song_id = song
        self.song_url = "https://music.163.com/api/v1/resource/comments/R_SO_4_" + self.song_id
        self.headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0',
    'Referer': 'http://music.163.com'
}
        self.client = pymongo.MongoClient('localhost', port=27017)
        self.db = self.client.test
        self.collection = self.db.hotComments
        self.session = requests.session()
        self.session = requests.get(self.song_url, headers=self.headers)
        self._save()

    def _get_comments(self, json_data):
        # get the json and find the hotcomments
        data = json.loads(json_data)
        for item in data.get("hotComments"):
            yield {
                'comment': item.get("content"),
                'likes': item.get("likedCount"),
                'user': item.get("user").get("nickname"),
                'date': self._get_time(str(item.get("time"))[:10])
            }

    def _get_time(self, timeStamp):
        timeArray = time.localtime(int(timeStamp))
        return time.strftime("%Y-%m-%d", timeArray)

    def _save(self):
        for hotComment in self._get_comments(self.session.text):
            self.collection.insert(hotComment)
        print("save successfully")



def main():
    song_url = input("Song_Url:")
    a = re.compile('id=\d+')
    song_id = a.findall(song_url)[0].replace('id=','')
    print(song_id)


if __name__ == "__main__":
    main()

运行效果:尝试爬取周杰伦的《晴天》

总结:内容没有什么技术含量,和普通的爬虫思路一样,不过这个Demo是爬取单首歌曲的,如果爬取歌曲过多,可能要做个代理池防止IP被封。

猜你喜欢

转载自www.cnblogs.com/AnswerW3I/p/9460606.html