Python爬蟲【實戰篇】bilibili視頻彈幕提取


兩個重要點

1.獲取彈幕的url是以 .xml 結尾

2.彈幕url的所需參數在視頻url響應的 javascript 中

先看代碼

import requests
from lxml import etree
import re

# 使用手機UA
headers = {
    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
}
# 視頻url
video_url = "https://m.bilibili.com/video/av37834086.html"
html = requests.get(url=video_url, headers=headers).content.decode('utf-8')
# 獲取彈幕url的參數
cid = re.findall(r"comment: '//comment.bilibili.com/' \+ (.*?) \+ '.xml',", html)

url = "https://comment.bilibili.com/" + cid[0] + ".xml"
print(url)
response = requests.get(url, headers=headers)
html = response.content

xml = etree.HTML(html)

# 提取數據
str_list = xml.xpath("//d/text()")
# 寫入文件
with open('bibi_xuxubaobao.txt', 'w', encoding='utf-8') as f:
    for line in str_list:
        f.write(line)
        f.write('\n')

先找到彈幕的url,以.xml結尾,所以先找到這串數字所在的位置,並獲取這串數字發起第二次請求

 

 

而這串數字就在 第一次請求的響應的JavaScript中,可以通過 re 正則表達式進行提取

 

 

 接下來的工作就是獲取彈幕url返回的所有彈幕數據,然后對響應進行數據處理。

代碼示例中使用的是 lxml 進行獲取。接着就是保存到個人本地文件中了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM