天天看点

简单三步,教你学会Python下载视频(三分钟上手)

💖 作者:大家好,我是阿旭😜

🎉 支持我:点赞👍收藏⭐️留言📝

📣 系列专栏:Python Pachong 🍁

下载b ili b ili视频~

项目代码

首先你需要先将PySimpleGUI和requests这两个模块安装到你的Python环境中。

pip install pysimplegui

pip install requests

接下来就是我们的代码啦❗️❗️❗️❗️

import PySimpleGUI as sg
import json
import requests

layout = [
    [sg.Text('视频地址:')],
    [sg.Input(key='video_url')],
    [sg.Text('保存地址:')],
    [sg.In(key='dir_name'), sg.FolderBrowse(target='dir_name')],
    [sg.Text('爬取前几集:')], 
    [sg.Slider(range=(1,10),orientation='horizontal', key='page')],
    [sg.Exit('取消'), sg.Button('确认')]
]

window = sg.Window('视频pa取', layout)
event, values = window.read()

save_path = values.get('dir_name')
b_url = values.get('video_url')

bvid = b_url.split('?')[0].split('/')[-1]

if not bvid:
    bvid = b_url.split('?')[0].split('/')[-2]

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36',
    'Referer': 'https://www.bilibili.com/'
}

cid_api = json.loads(requests.get(f'https://api.bilibili.com/x/player/pagelist?bvid={bvid}&jsonp=jsonp').text)
count = int(values.get('page'))

for i in range(count):
    cid = cid_api['data'][i]['cid']
    video_api = json.loads(requests.get(f'https://api.bilibili.com/x/player/playurl?bvid={bvid}&cid={cid}&qn=64').text)
    vurl = video_api['data']['durl'][0]['url']
    vr = requests.get(vurl, headers=headers)
    open(f'{save_path}/{i+1}.mp4','ab').write(vr.content)

sg.popup('Done!')
           

🎉 支持我:点赞👍收藏⭐️留言📝

📣 系列专栏:Python Pachong 🍁