PS:如有需要 Python学习资料 以及 解答 的小伙伴可以加点击下方链接自行获取
-
Python 3.6
-
Pycharm
-
requests
-
re
安装Python并添加到环境变量,pip安装需要的相关模块即可。
找一个弹幕比较多的视频爬取
以前的B站弹幕视频,点击查看历史的弹幕,会给你返回一个json数据,包含了所有的弹幕内容。
现在点击历史弹幕数据,同样是有数据加载出来,但是里面的都是乱码了。
请求这个链接还是会得到想要的数据内容。
只需要使用正则表达匹配中文字符就可以匹配出来
弹幕分页是根据日期来的,当点击 2021-01-01 的使用,返回的给我的数据并不是弹幕数据,而是所有的日期。
那么看到这里有人就会问了,那我想要爬取 2021-01-01 的弹幕数据怎么办?
这两个的url地址是不一样的,seg.so 才是弹幕数据url地址。
import requests
import re
def get_response(html_url):
headers = {
'cookie': '你自己的cookie',
'origin': 'www.bilibili.com',
'referer': 'www.bilibili.com/video/BV19E…',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
}
response = requests.get(url=html_url, headers=headers)
return response
def get_date(html_url):
response = get_response(html_url)
json_data = response.json()
date = json_data['data']
print(date)
return date
if name == 'main':
one_url = 'api.bilibili.com/x/v2/dm/his…'
get_date(one_url)
返回的数据是json数据,根据字典键值对取值就可以得到相关数据。
def main(html_url):
data = get_date(html_url)
for date in data:
url = f'api.bilibili.com/x/v2/dm/web…'
html_data = get_response(url).text
result = re.findall(".?([\u4E00-\u9FA5]+).?", html_data)
for i in result:
with open('B站弹幕.txt', mode='a', encoding='utf-8') as f:
f.write(i)
f.write('\n')
import requests
import re
def get_response(html_url):
headers = {
'cookie': '你自己的cookie',
'origin': 'www.bilibili.com',
'referer': 'www.bilibili.com/video/BV19E…',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
}
response = requests.get(url=html_url, headers=headers)
return response
收集整理了一份《2024年最新Python全套学习资料》免费送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Python知识点,真正体系化!