首页 > 编程语言 >Python爬虫爬取B站评论区

Python爬虫爬取B站评论区

时间:2023-08-02 15:22:19浏览次数:32  
标签:comment title Python 爬虫 爬取 url print append headers

写了两天,参考其他大牛的文章,摸着石头过河,终于写出了一个可以爬B站评论区的爬虫,人裂了……
致谢 :
致谢:
SmartCrane
马哥python说
该程序具有以下功能:
①输入B站视频链接,即可爬取B站评论区评论、IP、ID、点赞数、回复数,并保存在当前目录的以视频名字为标题的csv文件中。
②由视频链接可得视频标题、oid

注意事项:
①代码隐去了User-Agent和cookie,运行需补全,cookie不写入headers会爬不到IP属地,感谢马哥python说
②出现这个问题:

 comment = s['data']['replies'][i]
           ~~~~~~~~~~~~~~~~~~~~^^^
IndexError: list index out of range

随着评论区的退移,后面pages的评论页面对应的replies没有那么多项了(不像前面页码有17、18个,最后一面可能只有4、5个),例如有pages = 21面,评论共401条,则前20页每页都有20个replies , 而第21页只有一个reply,因此最后一页s['data']['replies'][2]就会报错.(其实这个报错也不影响最后输出的csv文件)
解决方案:适当减小main中页码的范围,找前面的页码就行了

import requests
import json
import time
import re

CommentList = [['IP属地' , '昵称' , 'ID' , '发表时间' , '评论内容' , '点赞数' , '回复数']] 
headers = {
    'authority': 'api.bilibili.com',
    'accept': 'application/json, text/plain, */*',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'cookie' : "请填入你的浏览器cookie" ,
    # change the cookie on time , or location cann't be get .
    'origin': 'https://www.bilibili.com',
    'referer': 'https://www.bilibili.com/video/BV1FG4y1Z7po/?spm_id_from=333.337.search-card.all.click&vd_source=69a50ad969074af9e79ad13b34b1a548',
    'sec-ch-ua': '"Chromium";v="106", "Microsoft Edge";v="106", "Not;A=Brand";v="99"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-site',
    'user-agent': '请填入你的User-agent'
}
    
def fetchURL(url):
    # response = requests.get(url = url , headers=headers)
    #print('Have got the html\n')
    # return response.text
    return requests.get(url=url , headers=headers).text

def parseHtml(html):
    s = json.loads(html)
    # print(f"the type of html is {type(html)}\n")  Str 
    #print(f"the type of s is {type(s['data']['replies'])}\n")       # Dictionary 
    # the function 'json.loads' turned string into dictionary
    '''
    CommentList = [] 
    hlist = []
    hlist.append('IP属地')
    hlist.append('昵称')
    hlist.append('ID')
    hlist.append('发表时间')
    hlist.append('评论内容')
    hlist.append('点赞数')
    hlist.append('回复数')
    CommentList.append(hlist)
    '''

    for i in range(0 , 15) :
        comment = s['data']['replies'][i]
        location = comment['reply_control']['location'][5:]
        #print(location[5:])
        uname = comment['member']['uname']
        ID = comment['member']['mid']
        ctime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(comment['ctime'])) # time of comment
        content = comment['content']['message']
        like = comment['like']
        rcount = comment['rcount']

        alist = []
        alist.append(location)
        alist.append(uname)
        alist.append(ID)
        alist.append(ctime)
        alist.append(content)
        alist.append(like)
        alist.append(rcount)
        CommentList.append(alist)
        
    
    #print('Have got CommentList\n')  
    #return CommentList


def Write2Csv(List , title ) :
    import pandas as pd
    dataframe = pd.DataFrame(List)
    # print(title)
    # filepath ='D:\Desktop\SpiderOfComment\CSVComment\\' + title + '.csv'
    filepath = title +'.csv'
    # print(filepath)
    dataframe.to_csv( filepath , index=False , sep = ',' ,  header = False , encoding='utf_8_sig')
    #dataframe.to_excel('')
    #print('Have written to the csv\n')

def GetTitle(url):
    page_text = requests.get(url=url , headers=headers).text
    #print(page_text)
    ex = '<h1 title="(.*?)".*?</h1>'
    title = re.findall(ex , page_text , re.S)[0]
    # print(type(title))
    return title

def GetOid(url):
    page_text = requests.get(url=url , headers=headers).text
    ex = '</script><script>window.__INITIAL_STATE__={"aid":(.*?),"bvid":'
    #  </script><script>window.__INITIAL_STATE__={"aid":269261816,"bvid"
    oid = re.findall(ex , page_text , re.S)[0]
    return oid 


if __name__ == '__main__' :
    print('Please input the url of the vedio:')
    temp_url = input()
    title = GetTitle(temp_url)
    # print(type(title))
    oid = GetOid(temp_url)
    url0 = 'https://api.bilibili.com/x/v2/reply?type=1&oid=' + oid + '&sort=2&pn='
    # print(url)
    print('Wait……')
    for i in range(1, 20):
        url = url0 + str(i)
        html = fetchURL(url) 
        parseHtml(html)
        # Write2Csv(CommentList)
        if(i%5==0):
            time.sleep(1)
    Write2Csv(CommentList , title)
    print('Success!\n')


    

标签:comment,title,Python,爬虫,爬取,url,print,append,headers
From: https://www.cnblogs.com/benkangpeng/p/17600683.html

相关文章

  • python最简单的传参方法-第一次见这种方法
    我又一个python文件,名为grounding_dino_demo.py,其代码为:fromgroundingdino.util.inferenceimportload_model,load_image,predict,annotate,Modelimportcv2CONFIG_PATH="GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py"CHECKPOINT_PATH=&......
  • 一周学会python1-开始
    1Python简介Python是一种相当流行(而且简单易学)的高级编程语言。本书将以直观的方式向你传授Python。即使你没有任何编程语言的经验,也能掌握Python的基础知识并加以运用。1.1什么是Python?Python一种高级编程语言,在编程界非常流行。它简单、通用,并包含大量第三方框架库。它......
  • python3 install 其他包 报:ModuleNotFoundError: No module named '_ctypes' 的问题
    python3install其他包报:ModuleNotFoundError:Nomodulenamed'_ctypes'的问题python2import_ctypes没有问题python3import_ctypes报上述错误,说明_ctypes确实无法导入。据网上资料显示时没有安装libdiff库,但使用yum安装后,还需要重新编译python3。但python3好......
  • scrapy源码分析:redis分布式爬虫队列中,priority值越大,优先级越高
    scrapy源码分析:redis分布式爬虫队列中,priority值越大,优先级越高一、背景scrapy爬虫项目中,遇到scrapy的priority属性,搞不懂priority的值越大优先级越高,还是值越小优先级越高#通过priority修改优先级returnscrapy.Request(url=request.url,dont_filter=True,callback=spider......
  • 安装python误操作影响yum报错处理
    一,如图:yum时报:liblber-2.4.so.2:cannotopensharedobjectfile:Nosuchfileordirectory二,是因为缺少一个包:openldap-xxxx.el7_6.x86_64.rpm(注意不同版本的linux系统有不同XX版的包)三,在官网找到对应版本的openldap包:http://ftp.pbone.net/mirror/ftp.scientificlinux......
  • python写入mongodb时间字段格式为ISO
     #!/usr/bin/envpython#coding=utf-8importtimefromdateutilimportparserfrompymongoimportMongoClientnow=parser.parse(time.strftime("%Y-%m-%d%H:%M:%S",time.localtime()))conn=MongoClient("192.168.1.135:28001",maxPoo......
  • 使用python写ros publisher和subscriber
    publisher#!/usr/bin/envpython#licenseremovedforbrevityimportrospyfromstd_msgs.msgimportStringdeftalker():pub=rospy.Publisher('chatter',String,queue_size=10)rospy.init_node('talker',anonymous=True)ra......
  • [oeasy]python0078_变量部分总结_variable_summary
    删除变量回忆上次内容上次研究了变量的死有生就有死原本的死是在程序退出的时候自动执行的也可以手动给变量执行死刑del  del(a)之后dir()就无法在当前作用域(scope)内观察到这个变量了也就是说a死了......
  • 如何在 Python 中打印对象的属性
    在Python编程语言中,对象是指由类或类型创建的实例。每个对象都有自己的属性,这些属性可以是变量或函数。通常,我们需要打印对象的属性来了解它的状态。本文将介绍如何在Python中打印对象的属性。1.使用dir()函数dir()函数是Python中的一个内置函数,它可以返回一个对象的所有......
  • [转载] 解决Pycharm中右键运行python程序时出现Run ‘pytest‘ in XXX.py
    1、在Pycharm中右键运行python程序时出现Run'pytest'inXXX.py,这是进入了Pytest模式。2、解决办法进入到File-Seetings-Tools-PythonintegratedTools页面,找到Testing下的Defaulttestrunner,把Pytest设置为Unittests就可以了————————————————原文链接:ht......