如何用Python爬取网易云两百万热歌( 二 )

节点下 , 可以通过div#hotsong-list li a 得到歌曲的Id, href, name # 但是 , 可以通过下面的textarea节点得到更为详细的data , 这个不能通过正则匹配[] , 不然会被一些歌曲名给套住 # 有些歌手没有热门歌曲 , 比如: https://music.163.com/#/artist?id=13226806,当接近200万首歌的数据爬取完毕之后 , 我们启动评论爬虫 , 主要工作就是遍历数据库中还没有更新“评论数”这个字段的歌曲id , 然后访问对应的评论api , 得到我们想要的评论数据 。
核心代码如下:
def start_requests(self): cursor = self.coll_song.find({'comments_cnt': {'$exists': False}}, no_cursor_timeout=True) for song_item in cursor: if self.settings.get('PARSE_ALL_COMMENTS'): limit, offset = 100, 0 elif self.settings.get('PARSE_HOT_COMMENTS'): limit, offset = 0, 0 else: limit, offset = 0, 1 comment_url = self.get_comment_page_url(song_item['song_id'], limit=limit, offset=offset) yield Request(comment_url, dont_filter=False, callback=self.parse, meta={'song_item': song_item, 'limit': limit, 'offset': offset}) cursor.close()def parse(self, response): json_data = https://www.isolves.com/it/cxkf/yy/Python/2019-11-11/json.loads(response.text) comment_item = CommentItem() comment_item['comment_url'] = response.url.split('?')[0] comment_item['crawl_time'] = datetime.now() comment_item['isMusician'] = json_data['isMusician'] comment_item['comments_cnt'] = comments_cnt = json_data['total'] comment_item['song_name'] = response.meta['song_item']['song_name'] comment_item['singer_name'] = response.meta['song_item']['singer_name'] comment_item['song_id'] = song_id = response.meta['song_item']['song_id'] for comment_info in json_data.get('comments'): comment_item.update(comment_info) comment_item['_id'] = comment_info['commentId'] yield comment_item for comment_info in json_data.get('hotComments'): comment_item.update(comment_info) comment_item['_id'] = comment_info['commentId'] yield comment_item if self.settings.get("PARSE_ALL_COMMENTS") and json_data['more']: response.meta['offset'] = new_offset = response.meta['offset'] + 10 yield Request(self.get_comment_page_url(song_id, offset=new_offset), callback=self.parse, dont_filter=False, meta=response.meta) else: song_item = SongItem() song_item['_id'] = response.meta['song_item']['song_id'] song_item['comments_cnt'] = comments_cnt yield song_item小结
本项目提供了一个爬取网易云音乐的可行路径 , 即歌手分类 → 歌手 → 歌手的专辑 → 专辑内的单曲 → 单曲的评论 , 是一个非常广度的路径 , 如果全程爬完能得到3万歌手、20万专辑、200万首单曲的必要信息 , 可根据这些信息做歌手、专辑、单曲排序 , 制作歌单、热点追踪等等 , 很有意义 。




推荐阅读