import requests
import re
import json
import pprint
import subprocess


url = 'https://www.bilibili.com/video/BV11S4y1a7X9/'
headers = {
    'referer': 'https://www.bilibili.com/',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
}

response = requests.get(url=url, headers=headers)
# print(response.text)

title = re.findall('<h1 title="(.*?)" class="video-title tit">', response.text)[0]


play_info = re.findall('<script>window.__playinfo__=(.*?)</script>', response.text)[0]
print(title)
# print(play_info)
json_data = json.loads(play_info)
# print(json_data)
# pprint.pprint(json_data)    


audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
video_url = json_data['data']['dash']['video'][0]['baseUrl']
print(audio_url)
print(video_url)


audio_content = requests.get(audio_url, headers=headers).content    
video_content = requests.get(video_url, headers=headers).content    

with open('video\\' + title + '.mp3', mode='wb') as f:
    f.write(audio_content)
with open('video\\' + title + '.mp4', mode='wb') as f:
    f.write(video_content)


COMMAND = f'ffmpeg -i video\\{title}.mp4 -i video\\{title}.mp3 -c:v copy -c:a aac -strict experimental video\\{title}output.mp4 '
subprocess.run(COMMAND, shell=True)