鱼C论坛

 找回密码
 立即注册
查看: 2629|回复: 6

[已解决]Python爬虫练习——爬取QQ音乐精彩评论(编码问题请高人指点!)

[复制链接]
发表于 2020-2-17 19:06:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
2020年2月17日,采用Requests模块以及正则表达式完成了一次爬虫练习…
爬取QQ音乐精彩评论代码如下(欢迎各位指正):
  1. import requests
  2. import re

  3. #获取网页源代码
  4. def get_code(url):
  5.     headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0)"
  6.                              " Gecko/20100101 Firefox/73.0"}
  7.     return requests.get(url, headers=headers).text


  8. #从原网页中提取songid
  9. song_url=input('请输入QQ音乐网页版网址(https://y.qq.com/n/yqq/song/x.html形式):')
  10. song_doc = get_code(song_url)
  11. id = re.findall('"songid":(.*?),"',song_doc)[0]
  12. name = re.findall('songname":"(.*?)"',song_doc)[0]
  13. tgt = int(input('请输入需要爬取的页数:'))
  14. #从js文件中提取评论
  15. list = []      #防止评论重复
  16. num = 0
  17. for number in range(1,tgt):
  18.     comment_url = "https://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg?g_tk" \
  19.                   "=5381&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset" \
  20.                   "=GB2312¬ice=0&platform=yqq&needNewCode=0&cid=205360772&reqtype" \
  21.                   "=2&biztype=1&topid=%s&cmd=6&needmusiccrit=0&pagenum=%d&pagesize=" \
  22.                   "15&ct=24&cv=10101010"%(id,number)
  23.     comment_doc = get_code(comment_url)
  24.     targets = re.findall('"rootcommentcontent":"(.*?)"',comment_doc)
  25.     for each in targets:
  26.         each = re.sub(r"([em](.*?)[/em])|(\\n)|(\\)|[|]",'',each)
  27.         if each in list:
  28.             pass
  29.         else:
  30.             file = open('热门评论\\'+name+'.txt', 'a')
  31.             try:
  32.                 num += 1
  33.                 num_st = str(num)
  34.                 list.append(each)
  35.                 each = re.sub('\[|\]', '', each)
  36.                 file.write('编号'+num_st+' '+each+'\n')
  37.                 print('第'+num_st+'个评论已爬取!')
  38.                 file.close()
  39.             except Exception as err:
  40.                 print(err)
  41.     print('爬取成功!请查看当先文件夹下歌名文本!')
复制代码
有时候会出现这样的错误——
  1. 'gbk' codec can't encode character '\xb4' in position 23:
  2. illegal multibyte sequence
复制代码
看来应该是编码的问题,但未找到解决方案…




最佳答案
2020-2-17 21:02:39

这样试试:

  1. import requests
  2. import re

  3. #获取网页源代码
  4. def get_code(url):
  5.     headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0)"
  6.                              " Gecko/20100101 Firefox/73.0"}
  7.     return requests.get(url, headers=headers).content.decode("utf-8")


  8. #从原网页中提取songid
  9. song_url=input('请输入QQ音乐网页版网址(https://y.qq.com/n/yqq/song/x.html形式):')
  10. song_doc = get_code(song_url)
  11. id = re.findall('"songid":(.*?),"',song_doc)[0]
  12. name = re.findall('songname":"(.*?)"',song_doc)[0]
  13. tgt = int(input('请输入需要爬取的页数:'))
  14. #从js文件中提取评论
  15. list = []      #防止评论重复
  16. num = 0
  17. for number in range(1,tgt):
  18.     comment_url = "https://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg?g_tk" \
  19.                   "=5381&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset" \
  20.                   "=GB2312¬ice=0&platform=yqq&needNewCode=0&cid=205360772&reqtype" \
  21.                   "=2&biztype=1&topid=%s&cmd=6&needmusiccrit=0&pagenum=%d&pagesize=" \
  22.                   "15&ct=24&cv=10101010"%(id,number)
  23.     comment_doc = get_code(comment_url)
  24.     targets = re.findall('"rootcommentcontent":"(.*?)"',comment_doc)
  25.     for each in targets:
  26.         each = re.sub(r"([em](.*?)[/em])|(\\n)|(\\)|[|]",'',each)
  27.         if each in list:
  28.             pass
  29.         else:
  30.             file = open('热门评论\\'+name+'.txt', 'a', encoding="utf-8")    # 修改
  31.             try:
  32.                 num += 1
  33.                 num_st = str(num)
  34.                 list.append(each)
  35.                 each = re.sub(r'\[|\]', '', each)
  36.                 file.write('编号'+num_st+' '+each+'\n')
  37.                 print('第'+num_st+'个评论已爬取!')
  38.                 file.close()
  39.             except Exception as err:
  40.                 print(err)
  41.     print('爬取成功!请查看当先文件夹下歌名文本!')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-2-17 19:37:11 | 显示全部楼层
  1. import requests
  2. import re

  3. #获取网页源代码
  4. def get_code(url):
  5.     headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0)"
  6.                              " Gecko/20100101 Firefox/73.0"}
  7.     return requests.get(url, headers=headers).content.decode("utf-8")


  8. #从原网页中提取songid
  9. song_url=input('请输入QQ音乐网页版网址(https://y.qq.com/n/yqq/song/x.html形式):')
  10. song_doc = get_code(song_url)
  11. id = re.findall('"songid":(.*?),"',song_doc)[0]
  12. name = re.findall('songname":"(.*?)"',song_doc)[0]
  13. tgt = int(input('请输入需要爬取的页数:'))
  14. #从js文件中提取评论
  15. list = []      #防止评论重复
  16. num = 0
  17. for number in range(1,tgt):
  18.     comment_url = "https://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg?g_tk" \
  19.                   "=5381&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset" \
  20.                   "=GB2312¬ice=0&platform=yqq&needNewCode=0&cid=205360772&reqtype" \
  21.                   "=2&biztype=1&topid=%s&cmd=6&needmusiccrit=0&pagenum=%d&pagesize=" \
  22.                   "15&ct=24&cv=10101010"%(id,number)
  23.     comment_doc = get_code(comment_url)
  24.     targets = re.findall('"rootcommentcontent":"(.*?)"',comment_doc)
  25.     for each in targets:
  26.         each = re.sub(r"([em](.*?)[/em])|(\\n)|(\\)|[|]",'',each)
  27.         if each in list:
  28.             pass
  29.         else:
  30.             file = open('热门评论\\'+name+'.txt', 'a')
  31.             try:
  32.                 num += 1
  33.                 num_st = str(num)
  34.                 list.append(each)
  35.                 each = re.sub(r'\[|\]', '', each)
  36.                 file.write('编号'+num_st+' '+each+'\n')
  37.                 print('第'+num_st+'个评论已爬取!')
  38.                 file.close()
  39.             except Exception as err:
  40.                 print(err)
  41.     print('爬取成功!请查看当先文件夹下歌名文本!')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-2-17 20:57:44 | 显示全部楼层
  1.     return requests.get(url, headers=headers).content.decode("utf-8")
复制代码

这一行代码修改过后依然会出现这样的情况...
  1. 'gbk' codec can't encode character '\u200b' in position 129: illegal multibyte sequence
复制代码

还是谢谢惹!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-17 20:58:00 | 显示全部楼层
Omed 发表于 2020-2-17 20:57
这一行代码修改过后依然会出现这样的情况...

还是谢谢惹!

把完整报错信息发上来。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-2-17 21:02:05 | 显示全部楼层
zltzlt 发表于 2020-2-17 20:58
把完整报错信息发上来。
  1. C:\Users\asus\AppData\Local\Programs\Python\Python37\python.exe C:/Users/asus/Desktop/爬虫/爬取网易云音乐热门评论/comment.py
  2. 请输入QQ音乐网页版网址(https://y.qq.com/n/yqq/song/x.html形式):https://y.qq.com/n/yqq/song/003BkIIU2kGTDn.html  
  3. 请输入需要爬取的页数:20
  4. Traceback (most recent call last):
  5.   File "C:/Users/asus/Desktop/爬虫/爬取网易云音乐热门评论/comment.py", line 37, in <module>
  6.     file.write('编号'+num_st+' '+each+'\n')
  7. UnicodeEncodeError: 'gbk' codec can't encode character '\xb4' in position 61: illegal multibyte sequence

  8. Process finished with exit code 1
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-17 21:02:39 | 显示全部楼层    本楼为最佳答案   

这样试试:

  1. import requests
  2. import re

  3. #获取网页源代码
  4. def get_code(url):
  5.     headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0)"
  6.                              " Gecko/20100101 Firefox/73.0"}
  7.     return requests.get(url, headers=headers).content.decode("utf-8")


  8. #从原网页中提取songid
  9. song_url=input('请输入QQ音乐网页版网址(https://y.qq.com/n/yqq/song/x.html形式):')
  10. song_doc = get_code(song_url)
  11. id = re.findall('"songid":(.*?),"',song_doc)[0]
  12. name = re.findall('songname":"(.*?)"',song_doc)[0]
  13. tgt = int(input('请输入需要爬取的页数:'))
  14. #从js文件中提取评论
  15. list = []      #防止评论重复
  16. num = 0
  17. for number in range(1,tgt):
  18.     comment_url = "https://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg?g_tk" \
  19.                   "=5381&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset" \
  20.                   "=GB2312&#172;ice=0&platform=yqq&needNewCode=0&cid=205360772&reqtype" \
  21.                   "=2&biztype=1&topid=%s&cmd=6&needmusiccrit=0&pagenum=%d&pagesize=" \
  22.                   "15&ct=24&cv=10101010"%(id,number)
  23.     comment_doc = get_code(comment_url)
  24.     targets = re.findall('"rootcommentcontent":"(.*?)"',comment_doc)
  25.     for each in targets:
  26.         each = re.sub(r"([em](.*?)[/em])|(\\n)|(\\)|[|]",'',each)
  27.         if each in list:
  28.             pass
  29.         else:
  30.             file = open('热门评论\\'+name+'.txt', 'a', encoding="utf-8")    # 修改
  31.             try:
  32.                 num += 1
  33.                 num_st = str(num)
  34.                 list.append(each)
  35.                 each = re.sub(r'\[|\]', '', each)
  36.                 file.write('编号'+num_st+' '+each+'\n')
  37.                 print('第'+num_st+'个评论已爬取!')
  38.                 file.close()
  39.             except Exception as err:
  40.                 print(err)
  41.     print('爬取成功!请查看当先文件夹下歌名文本!')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-2-17 21:28:38 | 显示全部楼层

这样可以的!非常感谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-3-2 23:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表