Bilibili Subtitle Extraction
When watching English-language courses on Bilibili, obtaining the subtitle files can be valuable for later review. While many resort to AI-powered transcription services, Bilibili actually provides subtitle data in JSON format, which can be extracted directly.
Downloading CC Subtitles
CC subtitles appear as the white text on the black bar below the video player. Not all videos have subtitles available.
To download:
- Open the video and enable subtitles
- Open the browser's Developer Tools (F12) and navigate to the Network tab
- Filter for
jsonrequests - Refresh the video page
- Locate the subtitle JSON file, copy all content, and save it to a
.txtfile - Rename the file extension from
.txtto.json
Batch Converting JSON Subtitles to Text Files
Place all JSON subtitle files in a dedicated folder containing only these filees (no subdirectories). All paths must use English characters.
import json
import os
def extract_subtitles(json_dir):
files = os.listdir(json_dir)
output_dir = os.path.join(json_dir, 'output')
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for json_file in files:
output_name = json_file[:-5] + '.txt'
subtitle_text = ''
line_count = 1
with open(os.path.join(json_dir, json_file), 'r', encoding='utf-8') as f:
data = json.load(f)
for entry in data['body']:
text = entry['content'].replace('\n', ' ')
subtitle_text += text + ' '
if text.endswith('.'):
line_count += 1
if line_count % 2 == 0:
subtitle_text += '\n\n'
with open(os.path.join(output_dir, output_name), 'w', encoding='utf-8') as f:
f.write(subtitle_text)
if __name__ == '__main__':
source_path = 'F:\\Code\\subtitles\\raw'
extract_subtitles(source_path)
Important Notes
- Update the
source_pathvariable with your actual JSON folder location - Clean up the output folder before running the script again to avoid errors, or use a new folder for each batch
- Requires Python to be installed on your system
Reference Implementation
# Directory listing example
import os
os.listdir('C:\\')
# ['$360Section', '$Recycle.Bin', ...]
# Path construction
os.path.join('C:\\', 'output')
# Returns: 'C:\\output'
# Directory existence check
os.path.exists('C:\\nonexistent')
# Returns: False