前言💨
本文的文字及圖片來源於網絡,僅供學習、交流使用,不具有任何商業用途,如有問題請及時聯系我們以作處理。
前文內容💨
PS:如有需要 Python學習資料
以及 解答
的小伙伴可以加點擊下方鏈接自行獲取
python免費學習資料以及群交流解答點擊即可加入
基本開發環境💨
- Python 3.6
- Pycharm
相關模塊的使用💨
- requests
- parsel
- csv
- 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': 'https://www.bilibili.com',
'referer': 'https://www.bilibili.com/video/BV19E41197Kc',
'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 = 'https://api.bilibili.com/x/v2/dm/history/index?type=1&oid=120004475&month=2021-01'
get_date(one_url)
返回的數據是json數據,根據字典鍵值對取值就可以得到相關數據。
四、💥保存數據(數據持久化)
def main(html_url):
data = get_date(html_url)
for date in data:
url = f'https://api.bilibili.com/x/v2/dm/web/history/seg.so?type=1&oid=120004475&date={date}'
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': 'https://www.bilibili.com',
'referer': 'https://www.bilibili.com/video/BV19E41197Kc',
'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
def save(content):
for i in content:
with open('B站彈幕.txt', mode='a', encoding='utf-8') as f:
f.write(i)
f.write('\n')
print(i)
def main(html_url):
data = get_date(html_url)
for date in data:
url = f'https://api.bilibili.com/x/v2/dm/web/history/seg.so?type=1&oid=120004475&date={date}'
html_data = get_response(url).text
result = re.findall(".*?([\u4E00-\u9FA5]+).*?", html_data)
save(result)
if __name__ == '__main__':
one_url = 'https://api.bilibili.com/x/v2/dm/history/index?type=1&oid=120004475&month=2021-01'
main(one_url)