Python爬虫采集网易云音乐热评实战( 三 )

  • .*
'#进行第一次筛选的正则表达式result=re.compile(pat1).findall(html)#用正则表达式进行筛选result=result[0]#获取tuple的第一个元素pat2=r'
  • (.*?)
  • ' #进行歌名筛选的正则表达式pat3=r'
  • .*?
  • '#进行歌ID筛选的正则表达式hot_song_name=re.compile(pat2).findall(result)#获取所有热门歌曲名称hot_song_id=re.compile(pat3).findall(result)#获取所有热门歌曲对应的Idreturn hot_song_name,hot_song_iddef get_hotComments(hot_song_name,hot_song_id):url='' + hot_song_id + '?csrf_token='#歌评urlheader={#请求头部'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}#post请求表单数据data=http://kandian.youth.cn/index/{'params':'zC7fzWBKxxsm6TZ3PiRjd056g9iGHtbtc8vjTpBXshKIboaPnUyAXKze+KNi9QiEz/IieyRnZfNztp7yvTFyBXOlVQP/JdYNZw2+GRQDg7grOR2ZjroqoOU2z0TNhy+qDHKSV8ZXOnxUF93w3DA51ADDQHB0IngL+v6N8KthdVZeZBe0d3EsUFS8ZJltNRUJ','encSecKey':'4801507e42c326dfc6b50539395a4fe417594f7cf122cf3d061d1447372ba3aa804541a8ae3b3811c081eb0f2b71827850af59af411a10a1795f7a16a5189d163bc9f67b3d1907f5e6fac652f7ef66e5a1f12d6949be851fcf4f39a0c2379580a040dc53b306d5c807bf313cc0e8f39bf7d35de691c497cda1d436b808549acc'}postdata=http://kandian.youth.cn/index/urllib.parse.urlencode(data).encode('utf8')#进行编码request=urllib.request.Request(url,headers=header,data=http://kandian.youth.cn/index/postdata)reponse=urllib.request.urlopen(request).read().decode('utf8')json_dict=json.loads(reponse)#获取jsonhot_commit=json_dict['hotComments']#获取json中的热门评论num=0fhandle=open('./song_comments','a')#写入文件fhandle.write(hot_song_name+':'+'\n')for item in hot_commit:num+=1fhandle.write(str(num)+'.'+item['content']+'\n')fhandle.write('\n==============================================\n\n') fhandle.close()hot_song_name,hot_song_id=get_all_hotSong()#获取热歌榜所有歌曲名称和idnum=0while num < len(hot_song_name):#保存所有热歌榜中的热评print('正在抓取第%d首歌曲热评...'%(num+1))get_hotComments(hot_song_name[num],hot_song_id[num])print('第%d首歌曲热评抓取成功'%(num+1))num+=1代码运行结果如下:
    Python爬虫采集网易云音乐热评实战文章插图
    ?
    对比一下网页上《如果我爱你》这首歌的歌评和我们保存下的歌评:
    Python爬虫采集网易云音乐热评实战文章插图
    ?
    Python爬虫采集网易云音乐热评实战文章插图
    ?
    【Python爬虫采集网易云音乐热评实战】信息无误~


    推荐阅读