鱼C论坛

 找回密码
 立即注册
查看: 1450|回复: 7

B站的评论爬取

[复制链接]
发表于 2021-11-28 12:49:32 | 显示全部楼层 |阅读模式
60鱼币
爬取视频评论爬取不出来

EQCIO61TLVO13$8O}CYQ1_L.png
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-12-4 22:15:59 | 显示全部楼层
  1. import time
  2. import json
  3. import requests
  4. import pymysql
  5. from pyquery import  PyQuery as pq

  6. def getNum(headers):
  7.     # 获取投币、点赞、收藏数
  8.     def get_num(clsName, doc):
  9.         sign = doc(clsName)
  10.         sign.find("i").remove()
  11.         sign.find("canvas").remove()
  12.         return sign.text()
  13.     global like, coin, collect
  14.     url = "https://www.bilibili.com/video/BV1s34y1R7u9?spm_id_from=333.851.b_7265636f6d6d656e64.3"
  15.     r = requests.get(url, headers=headers)
  16.     doc = pq(r.text)

  17.     like = get_num(".like", doc)
  18.     coin = get_num(".coin", doc)
  19.     collect = get_num(".collect", doc)

  20. # 获取页面评论数据
  21. def get_html(url):

  22.     try:
  23.         r = requests.get(url, timeout=50, headers=headers)
  24.         r.raise_for_status()
  25.         r.encoding = 'utf-8'
  26.     except:
  27.         print("请求发生错误")
  28.         return None
  29.     else:
  30.         return r.text

  31. def get_comments(url):
  32.     global commentsNum
  33.     comments = []
  34.     html = get_html(url)
  35.     if not html:
  36.         return None

  37.     try:
  38.         data = json.loads(html)
  39.     except:
  40.         print("JSON数据转化错误")

  41.     num = len(data['data']['replies'])  # 获取每页评论栏的数量

  42.     if not commentsNum:
  43.         commentsNum = data['data']['cursor']['all_count']

  44.     i = 0

  45.     while i < num:

  46.         comment = data['data']['replies'][i]  # 获取每栏信息
  47.         InfoDict = {}  # 存储每组信息字典
  48.         InfoDict['用户名'] = comment['member']['uname']
  49.         InfoDict['评论内容'] = comment['content']['message']
  50.         InfoDict['rpid'] = comment['rpid']
  51.         comments.append(InfoDict)
  52.         i += 1

  53.     return comments

  54. def WriteToFile(comments):
  55.     index = 0
  56.     with open('评论.txt', 'a+', encoding='utf-8') as f:
  57.         for comment in comments:
  58.             try:
  59.                 i = 1
  60.                 error = 0
  61.                 page = 1
  62.                 index += 1
  63.                 f.write('姓名:{}\t 评论内容:{}\t rpid: {} \n'
  64.                         .format(comment['用户名'], comment['评论内容'], comment['rpid']))

  65.                 while error == 0:
  66.                     url = "https://api.bilibili.com/x/v2/reply/reply?&jsonp=jsonp&pn=" + str(i) + \
  67.                           "&type=1&oid=807015981&ps=10&root=" + str(comment['rpid']) + \
  68.                           "&_=1638614197025"
  69.                     try:
  70.                         childComments = get_comments(url)

  71.                         for childComment in childComments:
  72.                             with open('子评论.txt', 'a+', encoding='utf-8') as f1:
  73.                                     f1.write('姓名:{}\t 评论内容:{}\t rpid: {} \n'
  74.                                             .format(childComment['用户名'], childComment['评论内容'], childComment['rpid']))

  75.                         i += 1
  76.                         print("\t正在爬取第", index, "条评论", "\t第", page, "子页")
  77.                         page = page + 1
  78.                         # 降低ip被封的风险,每爬2页 就歇1秒。
  79.                         if page % 2 == 0:
  80.                             time.sleep(1)
  81.                     except:
  82.                         error = 1

  83.             except:
  84.                 print("写文件时发生错误")

  85.     print('当前页面保存完成')

  86. def main():

  87.     getNum(headers)

  88.     error = 0
  89.     page = 1
  90.     endPage = 5 # 爬取评论的页数

  91.     while error == 0 and page <= endPage:

  92.         url = "https://api.bilibili.com/x/v2/reply/main?&jsonp=jsonp&next=" + str(
  93.             page) + "&type=1&oid=807015981&mode=3&plat=1&_=1634475863039"
  94.         try:
  95.             comments = get_comments(url)
  96.             if not comments:
  97.                 raise Exception
  98.             print("正在爬取第", page, "页")
  99.             WriteToFile(comments)
  100.             page = page + 1
  101.             # 降低ip被封的风险,每爬10页 就歇5秒。
  102.             if page % 10 == 0:
  103.                 time.sleep(5)

  104.         except:
  105.             error = 1

  106.     with open("(点赞 投币 收藏 评论)总数.txt", 'a+', encoding='utf-8') as f:
  107.         f.write("点赞数:{}\t 投币数:{}\t 收藏数:{}\t 评论数:{}\n".format(like, coin, collect, commentsNum))

  108. if __name__ == '__main__':
  109.     like = 0  # 点赞总数
  110.     coin = 0  # 投币总数
  111.     collect = 0  # 收藏总数
  112.     commentsNum = 0  # 评论总数

  113.     headers = {
  114.         'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  115.         'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) appleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
  116.     }

  117.     main()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-11-28 12:56:20 | 显示全部楼层
用Selenium爬取时, 爬出不出评论部分的html代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-11-28 13:22:35 | 显示全部楼层
你的代码呢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-11-28 16:07:21 | 显示全部楼层
  1. import  requests
  2. from requests.exceptions import RequestException
  3. import  pymysql
  4. from pyquery import  PyQuery as pq
  5. from selenium import webdriver
  6. from selenium.webdriver.common.by import By
  7. from selenium.webdriver.support.ui import WebDriverWait
  8. from selenium.webdriver.support import expected_conditions as EC

  9. def get_num(clsName, doc):
  10.     sign = doc(clsName)
  11.     sign.find("i").remove()
  12.     sign.find("canvas").remove()
  13.     return sign.text()

  14. browser = webdriver.Chrome()
  15. browser.get('https://www.bilibili.com/video/BV17P4y1V7BX?spm_id_from=333.851.b_7265636f6d6d656e64.1')
  16. wait = WebDriverWait(browser, 10)

  17. div = wait.until( EC.presence_of_element_located( (By.CSS_SELECTOR, ".comment-list") ))

  18. doc1 = pq(browser.page_source)

  19. div = doc1(".comment-list")
  20. print(div)


  21. like = get_num(".like", doc1)
  22. coin = get_num(".coin", doc1)
  23. collect = get_num(".collect", doc1)

  24. print(like, coin, collect)

  25. browser.close()


  26. def main():
  27.     pass

  28. if __name__ == '__main__':
  29.     main()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-11-28 16:08:02 | 显示全部楼层
  1. <div class="comment-list "/>
  2. 结果只有一个这个
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-11-29 09:11:34 | 显示全部楼层
直接请求接口省事
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-12-4 22:15:25 | 显示全部楼层
  1. import time
  2. import json
  3. import requests
  4. import pymysql
  5. from pyquery import  PyQuery as pq

  6. def getNum(headers):
  7.     # 获取投币、点赞、收藏数
  8.     def get_num(clsName, doc):
  9.         sign = doc(clsName)
  10.         sign.find("i").remove()
  11.         sign.find("canvas").remove()
  12.         return sign.text()
  13.     global like, coin, collect
  14.     url = "https://www.bilibili.com/video/BV1s34y1R7u9?spm_id_from=333.851.b_7265636f6d6d656e64.3"
  15.     r = requests.get(url, headers=headers)
  16.     doc = pq(r.text)

  17.     like = get_num(".like", doc)
  18.     coin = get_num(".coin", doc)
  19.     collect = get_num(".collect", doc)

  20. # 获取页面评论数据
  21. def get_html(url):

  22.     try:
  23.         r = requests.get(url, timeout=50, headers=headers)
  24.         r.raise_for_status()
  25.         r.encoding = 'utf-8'
  26.     except:
  27.         print("请求发生错误")
  28.         return None
  29.     else:
  30.         return r.text

  31. def get_comments(url):
  32.     global commentsNum
  33.     comments = []
  34.     html = get_html(url)
  35.     if not html:
  36.         return None

  37.     try:
  38.         data = json.loads(html)
  39.     except:
  40.         print("JSON数据转化错误")

  41.     num = len(data['data']['replies'])  # 获取每页评论栏的数量

  42.     if not commentsNum:
  43.         commentsNum = data['data']['cursor']['all_count']

  44.     i = 0

  45.     while i < num:

  46.         comment = data['data']['replies'][i]  # 获取每栏信息
  47.         InfoDict = {}  # 存储每组信息字典
  48.         InfoDict['用户名'] = comment['member']['uname']
  49.         InfoDict['评论内容'] = comment['content']['message']
  50.         InfoDict['rpid'] = comment['rpid']
  51.         comments.append(InfoDict)
  52.         i += 1

  53.     return comments

  54. def WriteToFile(comments):
  55.     index = 0
  56.     with open('评论.txt', 'a+', encoding='utf-8') as f:
  57.         for comment in comments:
  58.             try:
  59.                 i = 1
  60.                 error = 0
  61.                 page = 1
  62.                 index += 1
  63.                 f.write('姓名:{}\t 评论内容:{}\t rpid: {} \n'
  64.                         .format(comment['用户名'], comment['评论内容'], comment['rpid']))

  65.                 while error == 0:
  66.                     url = "https://api.bilibili.com/x/v2/reply/reply?&jsonp=jsonp&pn=" + str(i) + \
  67.                           "&type=1&oid=807015981&ps=10&root=" + str(comment['rpid']) + \
  68.                           "&_=1638614197025"
  69.                     try:
  70.                         childComments = get_comments(url)

  71.                         for childComment in childComments:
  72.                             with open('子评论.txt', 'a+', encoding='utf-8') as f1:
  73.                                     f1.write('姓名:{}\t 评论内容:{}\t rpid: {} \n'
  74.                                             .format(childComment['用户名'], childComment['评论内容'], childComment['rpid']))

  75.                         i += 1
  76.                         print("\t正在爬取第", index, "条评论", "\t第", page, "子页")
  77.                         page = page + 1
  78.                         # 降低ip被封的风险,每爬2页 就歇1秒。
  79.                         if page % 2 == 0:
  80.                             time.sleep(1)
  81.                     except:
  82.                         error = 1

  83.             except:
  84.                 print("写文件时发生错误")

  85.     print('当前页面保存完成')

  86. def main():

  87.     getNum(headers)

  88.     error = 0
  89.     page = 1
  90.     endPage = 5 # 爬取评论的页数

  91.     while error == 0 and page <= endPage:

  92.         url = "https://api.bilibili.com/x/v2/reply/main?&jsonp=jsonp&next=" + str(
  93.             page) + "&type=1&oid=807015981&mode=3&plat=1&_=1634475863039"
  94.         try:
  95.             comments = get_comments(url)
  96.             if not comments:
  97.                 raise Exception
  98.             print("正在爬取第", page, "页")
  99.             WriteToFile(comments)
  100.             page = page + 1
  101.             # 降低ip被封的风险,每爬10页 就歇5秒。
  102.             if page % 10 == 0:
  103.                 time.sleep(5)

  104.         except:
  105.             error = 1

  106.     with open("(点赞 投币 收藏 评论)总数.txt", 'a+', encoding='utf-8') as f:
  107.         f.write("点赞数:{}\t 投币数:{}\t 收藏数:{}\t 评论数:{}\n".format(like, coin, collect, commentsNum))

  108. if __name__ == '__main__':
  109.     like = 0  # 点赞总数
  110.     coin = 0  # 投币总数
  111.     collect = 0  # 收藏总数
  112.     commentsNum = 0  # 评论总数

  113.     headers = {
  114.         'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  115.         'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) appleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
  116.     }

  117.     main()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-19 15:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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