python爬取bili评论

实例操作。非常规页面爬取

import requests
import lxml.html
import json

class Bili:
    def __init__(self):
        pass
    def getMsg(self,url):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6788.400 QQBrowser/10.3.2727.400'}
        html=requests.get(url=url,headers=headers).content.decode('utf-8')
        str1=json.loads(html)
        for i in str1['data']['replies']:
            print(i['member']['uname'],i['member']['sex'] ,'   ' ,i['content']['message'])
            if i['replies']==None:
                pass
            else:
                for k in i['replies']:
                    print(k['member']['uname'], k['member']['sex'], '   ', k['content']['message'])
if __name__ == '__main__':
    bl=Bili()
    id=46820799
    for i in range(20):
        try:
            url1='https://api.bilibili.com/x/v2/reply?&jsonp=jsonp&pn={}&type=1&oid={}&sort=0'.format(i,id)
            bl.getMsg(url1)
        except Exception:
            pass

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
B站视频评论,可以使用Python中的requests和beautifulsoup库。以下是一个简单的例子: 首先,我们需要找到要评论的视频页面,并复制视频的AV号。 然后,我们可以使用以下代码来获评论数据: ```python import requests from bs4 import BeautifulSoup av_number = 'AV号' # 替换为要的视频的AV号 url = f'https://www.bilibili.com/video/{av_number}/' # 发送请求,获页面内容 response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 查找评论元素 comments = soup.find_all('div', {'class': 'comment'}) # 提评论内容 for comment in comments: content = comment.find('div', {'class': 'text'}).text.strip() print(content) ``` 这段代码使用requests库发送GET请求,然后使用beautifulsoup库解析页面内容。我们通过查找“comment”类的div元素来获评论,并从每个评论中提评论内容。 注意:为了避免被B站反虫机制限制,我们需要在请求头中添加一些信息,使其看起来像是一个普通的用户在浏览网页。可以将以下代码添加到请求头中: ```python headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299', 'Referer': url, 'Cookie': 'SESSDATA=xxxxxxxxxx; bili_jct=xxxxxxxxxx;' } response = requests.get(url, headers=headers) ``` 其中,User-Agent代表浏览器的信息,Referer则表示当前请求来源,Cookie是用户的登录信息。你需要将Cookie和Referer替换为你自己的信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wgnms

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值