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