B站視頻爬取
# 糖醋慕雨的快樂時光
import requests
import re
import time
import pprint ?# 導入格式化輸出模塊
import json
import subprocess ?# 導入進程模塊
import os
# 發(fā)送請求
# https://www.bilibili.com/video/BV1U541137Eb?spm_id_from=333.337.search-card.all.click
url = input('請輸入B站視頻鏈接:')
headers = {
? ?'referer': 'https://www.bilibili.com/a';, ?# 防盜鏈 告訴服務器 我們請求的url網(wǎng)址是從哪里跳轉過來的
? ?'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
}
response = requests.get(url=url, headers=headers)
html = response.text
# print(response) ?# <response[200]>響應對象
# 解析數(shù)據(jù)
time.sleep(2)
# <h1 id="video-title" title="(.*?)" class="video-title"><a target="_blank" class="activity">活動作品</a><span class="tit">漂亮的穿旗袍美女剪超短發(fā)</span></h1>
# 視頻標題
# title = re.findall('<h1 title="(.*?)" class="video-title tit">.*?</h1>', html, re.S)[0]
# title = re.sub(r'[\/:-?*&"<>| 》《]', '', title)
title = '魔女之旅素材庫'
html_data = re.findall('<script>window.__playinfo__=(.*?)</script>', html)[0] ?# 字符串類型
# print(title)
# print(html_data)
# 將html轉化成字典
json_data = json.loads(html_data)
# print(json_data)
# pprint.pprint(json_data)
# print(type(json_data))
# 字典取值
audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
video_url = json_data['data']['dash']['video'][0]['baseUrl']
# print(audio_url)
audio_content = requests.get(url=audio_url, headers=headers).content
video_content = requests.get(url=video_url, headers=headers).content
with open(title + '.mp3', 'wb') as f:
? ?f.write(audio_content)
with open(title + '.mp4', 'wb') as f:
? ?f.write(video_content)
print(title, '下載完成')
title1 = title.replace(' ', '')
print(title)
cmd = f"ffmpeg -i {title}.mp4 -i {title}.mp3 -c:v copy -c:a aac -strict experimental {title}output.mp4"
# cmd = f'ffmpeg -i {title}.mp4 -i {title}.mp3 {title}output.mp4'
subprocess.run(cmd, shell=True)
os.remove(f'{title}.mp4')
os.remove(f'{title}.mp3')
print(title, '視頻合成完成')