python 爬取B站原视频的实例代码
作者:崔笑颜 发布时间:2023-03-06 04:08:43
标签:python,爬取,B站,视频
B站原视频爬取,我就不多说直接上代码。直接运行就好。
B站是把视频和音频分开。要把2个合并起来使用。这个需要分析才能看出来。然后就是登陆这块是比较难的。
import os
import re
import argparse
import subprocess
import prettytable
from DecryptLogin import login
'''B站类'''
class Bilibili():
def __init__(self, username, password, **kwargs):
self.username = username
self.password = password
self.session = Bilibili.login(username, password)
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36'
}
self.user_info_url = 'http://api.bilibili.com/x/space/acc/info'
self.submit_videos_url = 'http://space.bilibili.com/ajax/member/getSubmitVideos'
self.view_url = 'http://api.bilibili.com/x/web-interface/view'
self.video_player_url = 'http://api.bilibili.com/x/player/playurl'
'''运行主程序'''
def run(self):
while True:
userid = input('请输入目标用户ID(例:345993405)(我的一个LOL好友凯撒可以关注他一下 谢谢) ——> ')
user_info = self.__getUserInfo(userid)
tb = prettytable.PrettyTable()
tb.field_names = list(user_info.keys())
tb.add_row(list(user_info.values()))
print('获取的用户信息如下:')
print(tb)
is_download = input('是否下载该用户的所有视频(y/n, 默认: y) ——> ')
if is_download == 'y' or is_download == 'yes' or not is_download:
self.__downloadVideos(userid)
'''根据userid获得该用户基本信息'''
def __getUserInfo(self, userid):
params = {'mid': userid, 'jsonp': 'jsonp'}
res = self.session.get(self.user_info_url, params=params, headers=self.headers)
res_json = res.json()
user_info = {
'用户名': res_json['data']['name'],
'性别': res_json['data']['sex'],
'个性签名': res_json['data']['sign'],
'用户等级': res_json['data']['level'],
'生日': res_json['data']['birthday']
}
return user_info
'''下载目标用户的所有视频'''
def __downloadVideos(self, userid):
if not os.path.exists(userid):
os.mkdir(userid)
# 非会员用户只能下载到高清1080P
quality = [('16', '流畅 360P'),
('32', '清晰 480P'),
('64', '高清 720P'),
('74', '高清 720P60'),
('80', '高清 1080P'),
('112', '高清 1080P+'),
('116', '高清 1080P60')][-3]
# 获得用户的视频基本信息
video_info = {'aids': [], 'cid_parts': [], 'titles': [], 'links': [], 'down_flags': []}
params = {'mid': userid, 'pagesize': 30, 'tid': 0, 'page': 1, 'order': 'pubdate'}
while True:
res = self.session.get(self.submit_videos_url, headers=self.headers, params=params)
res_json = res.json()
for item in res_json['data']['vlist']:
video_info['aids'].append(item['aid'])
if len(video_info['aids']) < int(res_json['data']['count']):
params['page'] += 1
else:
break
for aid in video_info['aids']:
params = {'aid': aid}
res = self.session.get(self.view_url, headers=self.headers, params=params)
cid_part = []
for page in res.json()['data']['pages']:
cid_part.append([page['cid'], page['part']])
video_info['cid_parts'].append(cid_part)
title = res.json()['data']['title']
title = re.sub(r"[‘'\/\\\:\*\?\"\<\>\|\s']", ' ', title)
video_info['titles'].append(title)
print('共获取到用户ID<%s>的<%d>个视频...' % (userid, len(video_info['titles'])))
for idx in range(len(video_info['titles'])):
aid = video_info['aids'][idx]
cid_part = video_info['cid_parts'][idx]
link = []
down_flag = False
for cid, part in cid_part:
params = {'avid': aid, 'cid': cid, 'qn': quality, 'otype': 'json', 'fnver': 0, 'fnval': 16}
res = self.session.get(self.video_player_url, params=params, headers=self.headers)
res_json = res.json()
if 'dash' in res_json['data']:
down_flag = True
v, a = res_json['data']['dash']['video'][0], res_json['data']['dash']['audio'][0]
link_v = [v['baseUrl']]
link_a = [a['baseUrl']]
if v['backup_url']:
for item in v['backup_url']:
link_v.append(item)
if a['backup_url']:
for item in a['backup_url']:
link_a.append(item)
link = [link_v, link_a]
else:
link = [res_json['data']['durl'][-1]['url']]
if res_json['data']['durl'][-1]['backup_url']:
for item in res_json['data']['durl'][-1]['backup_url']:
link.append(item)
video_info['links'].append(link)
video_info['down_flags'].append(down_flag)
# 开始下载
out_pipe_quiet = subprocess.PIPE
out_pipe = None
aria2c_path = os.path.join(os.getcwd(), 'tools/aria2c')
ffmpeg_path = os.path.join(os.getcwd(), 'tools/ffmpeg')
for idx in range(len(video_info['titles'])):
title = video_info['titles'][idx]
aid = video_info['aids'][idx]
down_flag = video_info['down_flags'][idx]
print('正在下载视频<%s>...' % title)
if down_flag:
link_v, link_a = video_info['links'][idx]
# --视频
url = '"{}"'.format('" "'.join(link_v))
command = '{} -c -k 1M -x {} -d "{}" -o "{}" --referer="https://www.bilibili.com/video/av{}" {} {}'
command = command.format(aria2c_path, len(link_v), userid, title+'.flv', aid, "", url)
print(command)
process = subprocess.Popen(command, stdout=out_pipe, stderr=out_pipe, shell=True)
process.wait()
# --音频
url = '"{}"'.format('" "'.join(link_a))
command = '{} -c -k 1M -x {} -d "{}" -o "{}" --referer="https://www.bilibili.com/video/av{}" {} {}'
command = command.format(aria2c_path, len(link_v), userid, title+'.aac', aid, "", url)
print(command)
process = subprocess.Popen(command, stdout=out_pipe, stderr=out_pipe, shell=True)
process.wait()
# --合并
command = '{} -i "{}" -i "{}" -c copy -f mp4 -y "{}"'
command = command.format(ffmpeg_path, os.path.join(userid, title+'.flv'), os.path.join(userid, title+'.aac'), os.path.join(userid, title+'.mp4'))
print(command)
process = subprocess.Popen(command, stdout=out_pipe, stderr=out_pipe_quiet, shell=True)
process.wait()
os.remove(os.path.join(userid, title+'.flv'))
os.remove(os.path.join(userid, title+'.aac'))
else:
link = video_info['links'][idx]
url = '"{}"'.format('" "'.join(link))
command = '{} -c -k 1M -x {} -d "{}" -o "{}" --referer="https://www.bilibili.com/video/av{}" {} {}'
command = command.format(aria2c_path, len(link), userid, title+'.flv', aid, "", url)
process = subprocess.Popen(command, stdout=out_pipe, stderr=out_pipe, shell=True)
process.wait()
os.rename(os.path.join(userid, title+'.flv'), os.path.join(userid, title+'.mp4'))
print('所有视频下载完成, 该用户所有视频保存在<%s>文件夹中...' % (userid))
'''借助大佬开源的库来登录B站'''
@staticmethod
def login(username, password):
_, session = login.Login().bilibili(username, password)
return session
'''run'''
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='下载B站指定用户的所有视频(仅支持Windows下使用)')
parser.add_argument('--username', dest='username', help='xxx', type=str, required=True)
parser.add_argument('--password', dest='password', help='xxxx', type=str, required=True)
print(parser)
args = parser.parse_args(['--password', 'xxxx','--username', 'xxx'])
# args = parser.parse_args(['--password', 'FOO'])
print('5')
bili = Bilibili(args.username, args.password)
bili.run()
把账号密码填上就行。这是我根据一个微信公众号Charles大佬的想法写的。大家可以去关注他一下。
来源:https://cloud.tencent.com/developer/article/1640079


猜你喜欢
- win10系统本地安装MySQL8.0.20,亲测可用,也是参考了其他大神的操作1. 下载Mysql ,官网下载地址:MySQL官网:链接直
- offsetWidth 包括边框的宽度 clientWidth 不包括<table bord
- 实现html界面<!DOCTYPE html><html><head><title>Sele
- 前言:我们都知道事务的几种性质,数据库为了维护这些性质,尤其是一致性和隔离性,一般使用加锁这种方式。同时数据库又是个高并发的应用,同一时间会
- 使用tkinter实现下拉多选框效果如图:1、选择一些选项2、全选选项代码如下:import tkinterfrom ComBoPicker
- 本文实例为大家分享了用vue实现加载页的具体代码,供大家参考,具体内容如下<template>? ? <div class
- Python input 等待键盘输入,超时选择默认值,释放input,之后重新进入等待键盘输入状态,直到用户输入可用数据。一、调用 fun
- 首先需要安装pyinstaller库。pip install pyinstallerexe程序打包步骤cmd 进入要编译的python文件所
- md5是一种常见不可逆加密算法,使用简单,计算速度快,在很多场景下都会用到,比如:给用户上传的文件命名,数据库中保存的用户密码,下载文件后检
- 最近在做项目的时候经常会用到定时任务,由于我的项目是使用Java来开发,用的是SpringBoot框架,因此要实现这个定时任务其实并不难。后
- 一、正则表达式的特殊字符介绍正则表达式^ 匹配行首 &nb
- 把程序重新写了一遍,日期下拉选择器,可自定义日期范围。使用了一个技巧获取指定月份的天数。演示页面:DateSelector.htm 程序代码
- 错误类型: Microsoft JET Database Engine (0x80004005) 不能使用 '';文件已在使
- 最近要做个从 pdf 文件中抽取文本内容的工具,大概查了一下 python 里可以使用 pdfminer 来实现。下面就看看怎样使用吧。PD
- mysql 加了 skip-name-resolve不能链接的问题,要确认 MySql 是否采用过主机名的授权在 MySql Server
- 用VBS语言实现的一个简单网页计算器,功能:可以进行加法、减法、乘法、除法、取反、开根号、及指数运算。虽然简单但是比起windows xp自
- 经常在前端面试或是和其他同行沟通是,在谈到构造在JS定义构造函数的方法是最好使用原型的方式:将方法定义到构造方法的prototype上,这样
- --BEGIN DISTRIBUTED TRANSACTION [transactionname]--标志一个由分布式事务处理协调器MSDT
- 使用mysql主从复制的好处有:1、采用主从服务器这种架构,稳定性得以提升。如果主服务器发生故障,我们可以使用从服务器来提供服务。2、在主从
- 译者按:在iOS HIG已经强大经典了N年之后,Android终于推出了一套比较系统的HIG(大概是为了配合Android 4.0 Ice