From 9f80eb39f058aa30306d08b726321de02265e20a Mon Sep 17 00:00:00 2001 From: Zhao Zuohong Date: Sat, 18 Feb 2023 22:20:47 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=A9=20Add=20geturl=20function?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- snippets/geturl.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 snippets/geturl.py diff --git a/snippets/geturl.py b/snippets/geturl.py new file mode 100644 index 0000000..b217664 --- /dev/null +++ b/snippets/geturl.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 + +from bilibili_api import video, sync + + +def geturl(vn: str) -> str: + """Get audio download URL from AV or BV number with bilibili-api-python. + + Parameters + ---------- + vn : str + AV or BV number. + + Returns + ------- + str + URL of audio stream. + + Raises + ------ + InvalidVideoNumberException + If the format of AV or BV video number is invalid. + BiliBiliAPIException + If bilibili-api-python raises exception. + BadVideoException + If video is in flv format. + """ + + class InvalidVideoNumberException(Exception): + pass + + class BiliBiliAPIException(Exception): + pass + + class BadVideoException(Exception): + pass + + if len(vn) <= 2: + raise InvalidVideoNumberException("Video number too short!") + if vn[:2].upper() == "AV": + if not vn[2:].isnumeric(): + raise InvalidVideoNumberException("Invalid AV video number!") + else: + v = video.Video(aid="AV" + vn[2:]) + if vn[:2].upper() != "BV": + raise InvalidVideoNumberException("Invalid video number!") + else: + v = video.Video(bvid="BV" + vn[2:]) + + try: + download_url_data = sync(v.get_download_url(0)) + detecter = video.VideoDownloadURLDataDetecter(data=download_url_data) + streams = detecter.detect_best_streams() + except: + raise BiliBiliAPIException("Error happens with bilibili-api-python.") + if detecter.check_flv_stream() == True: + raise BadVideoException("Video is only available in flv format.") + + return streams[1].url