ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

B站短评爬取优化版(来源知乎)

2021-05-02 13:32:49  阅读:169  来源: 互联网

标签:comment 短评 知乎 url 爬取 headers json import total


纯小白,这个代码我花了额一天时间优化(其实不用一天,主要是找资料调试费的时间多)

博客园发布:

import json
import random
import time
import tkinter as tk
from tkinter import filedialog
import requests
root = tk.Tk()
root.withdraw()
FilePath = filedialog.askopenfilename()  # 一般这个直接选择文件,会比较符合人们的使用习惯和软件的用户体验
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}  # 伪装成浏览器,绕过反爬
url = 'https://api.bilibili.com/pgc/review/short/list?media_id=28223053&ps=20&sort=1'  # media_id就是动画id,sort排序,默认0,最新1
# 发送get请求
w = requests.get(url, headers=headers).text
json_comment = json.loads(w)
total = json_comment['data']['list']  # url中list中存储的内容
num = json_comment['data']['total']  # total中的内容,一共有多少个url
s = json_comment['data']  # url中的所有内容
j = 0
while j < num:
    total = json_comment['data']['list']
    for i in range(len(total)):
        comment = total[i]['content']  # 获取url中的评论
        print(comment)
    j += 1
    next = json_comment['data']['next']  # 获取next中的内容
    next1 = str(next)
    url1 = url + '&cursor=' + next1
    response = requests.get(url1, headers=headers).text
    json_comment = json.loads(response)
    time.sleep(random.choice([0.3, 0.5]))  # 随机延时0.3或者0.5秒,可调时间 要无延时可删除此行
    with open(FilePath, 'a+', encoding='utf-8', ) as f:  # 可选择文件夹
        # "a" - 追加 - 会追加到文件的末尾"w" - 写入 - 会覆盖任何已有的内容
        f.write(comment + '\n')

 

标签:comment,短评,知乎,url,爬取,headers,json,import,total
来源: https://www.cnblogs.com/bilibili2translation/p/14725577.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有