当你写了个 bug 却刚好能够运行(4)

· · 科技·工程

最近发现 B 站的随机播放实际并不随机,于是自己写了个简单的 Python 音乐播放器。

可以爬取 up 主 @JLRS-LeoFM 的所有视频然后随机播放。

支持上一首、下一首、暂停功能。

upd: 新增“收藏”功能。

upd: 新增“查看歌单”功能。

目前只能在控制台操作。 :::info[upd on] 2025-9-1

version 4.1.2

:::success[Code]{open}

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
import time, random, json, msvcrt, os, winsound, re
version = '4.1.2'

#启动模块
print('启动中,请稍后。。。')
os.system(f"title Dou's music player {version}")
options = Options()
options.add_argument('--disable-gpu')
options.add_argument("--log-level=3")
options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.5481.50 Safari/537.36')
driver = webdriver.Edge(options = options)
driver.implicitly_wait(10)
driver.get('https://www.bilibili.com/')

#登录模块
print('自动登录中。。。')
driver.delete_all_cookies()
try:
    with open('bilibili-cookies.json', 'r') as file:
        cookies = json.load(file)
        for cookie in cookies: driver.add_cookie(cookie)
        driver.refresh()
except Exception as e: print('自动登录失败。')
print('请确认登录后在控制台按下任意键。如自动登录失败,请手动登录。')
print('请按任意键继续. . .', end='', flush=True); winsound.MessageBeep()
while not msvcrt.kbhit(): pass
msvcrt.getch(); print('\r已完成登录。       ')
with open('bilibili-cookies.json', 'w') as file:
    json.dump(driver.get_cookies(), file, indent=4)

#爬取模块
video = []; name = {}
def crawl():
    global video, name
    if os.path.exists('bilibili-videos.json'):
        with open('bilibili-videos.json', 'r', encoding='utf-8') as file:
            name = json.load(file); video = list(name.keys())
            print(f"已载入 {len(video)} 首歌")
    os.system('cls & mode con: cols=120 lines=30')
    print('正在爬取歌单,请不要操控浏览器(按Enter结束)')
    driver.get('https://space.bilibili.com/3493093607213343/upload/video')
    while True:
        try:
            while msvcrt.kbhit():
                if msvcrt.getch() == b'\r': return
            time.sleep(5)
            elements = driver.find_elements(By.TAG_NAME, 'a')
            for e in elements:
                BV = e.get_attribute("href")[31:43]
                if BV in video: continue
                if '百万豪装录音棚' in e.text:
                    name[BV] = e.text; video.append(BV)
                    print('已爬取 ', e.text)
                os.system(f"title [{len(video)}] Dou's music player {version}")
        except Exception as e: continue
        try:
            driver.find_element(By.XPATH, '//*[@id="app"]/main/div[1]/div[2]/div/div[3]/div/div[1]/button[11]').click()
        except Exception as e: return

while True:
    crawl(); winsound.MessageBeep()
    while msvcrt.kbhit(): msvcrt.getch()
    with open('bilibili-videos.json', 'w', encoding='utf-8') as file:
        json.dump(name, file, ensure_ascii=False, indent=4)
    print(f'爬取完毕,共爬取了 {len(video)} 首歌')
    print('按任意键开始播放. . .', end='', flush=True)
    while not msvcrt.kbhit(): pass
    if msvcrt.getch() != b'\x08': os.system('cls'); break
random.shuffle(video)
while msvcrt.kbhit(): msvcrt.getch()

#播放器
col = [31, 32, 33, 36, 91, 92, 93, 94, 95, 96]
def play(url, name):
    os.system("cls & title ^" + '^'.join(name))
    print(f'即将播放:{name}'); driver.get(url); time.sleep(2)
    os.system(f'mode con: cols={100 if len(name)<45 else 120} lines=4')
    Video = driver.find_element(By.TAG_NAME, 'video')
    fav = driver.find_element(By.CLASS_NAME, 'video-fav'); fav_fail = ''
    while True:
        dur = int(driver.execute_script('return arguments[0].duration;', Video))
        now = int(driver.execute_script('return arguments[0].currentTime;', Video))
        pause = bool(driver.execute_script("return arguments[0].paused;", Video))
        progress = int(now / dur * 66) + 1; bar = '=' * progress + '-' * (66 - progress)
        faved = 'on' in fav.get_attribute('class').split(' '); os.system('cls')
        print(f'已暂停:{name}' if pause else f'\x1b[{random.choice(col)}m正在播放:{name}\x1b[0m')
        print(f'[{now // 60:02}:{now % 60:02} {bar} {dur // 60:02}:{dur % 60:02}]')
        print(f"←:上一首   ↓:{'开始' if pause else '暂停'}   →:下一首   ", end='')
        print(f"Enter:{'取消收藏' if faved else '收藏'}{fav_fail}   Tab:查看歌单", end='')
        print(f"\x1b[2;1H\x1b[{progress + 7}C", end='', flush=True)
        if fav_fail == '失败': fav_fail = ''
        if msvcrt.kbhit():
            key = msvcrt.getch()
            if key == b'\xe0' or key == b'\x00': key = msvcrt.getch()
            if key == b'K' or key == b'a': return 'prev'
            if key == b'M' or key == b'd': return 'next'
            if key == b'P' or key == b's':
                if pause: driver.execute_script('arguments[0].play();', Video)
                else: driver.execute_script('arguments[0].pause();', Video)
                pause = not pause
            if key == b'\r':
                try:
                    ActionChains(driver).send_keys('e').perform(); time.sleep(0.2)
                    driver.find_element(By.CSS_SELECTOR, "[title='歌单']").click()
                    driver.find_element(By.CLASS_NAME, 'submit-move').click()
                except Exception as e: fav_fail = '失败'
            if key == b'\t': return 'view'
            while msvcrt.kbhit(): msvcrt.getch()
        if now + 1 >= dur: time.sleep(2); return 'next'
        time.sleep(0.5)

#播放模块
played, dislike = [], set()
BV = video.pop()
while True:
    try:
        if BV in dislike: status = 'next'
        else: status = play('https://www.bilibili.com/video/' + BV, name[BV])
        os.system(f"title Dou's music player {version}"); driver.get('about:blank')
        if status == 'view':
            now = 1
            while True:
                os.system('cls')
                print(f"已播放:{len(played)} / 未播放:{len(video)} / 已删除:{len(dislike)}")
                if now == 1: print(f"←当前播放→:{name[BV]}")
                if now == 0: print(f"上一首→:{name[played[-1]] if played else '无'}")
                if now == 2: print(f"←下一首:{name[video[-1]] if video else '无'}")
                print("Tab:播放当前     Del:删除当前     Ins:重置歌单", end='', flush=True)
                while msvcrt.kbhit(): msvcrt.getch()
                while not msvcrt.kbhit(): pass
                key = msvcrt.getch()
                if key == b'\xe0': key = msvcrt.getch()
                if key == b'K' or key == b'a': now = max(0, now - 1)
                if key == b'M' or key == b'd': now = min(2, now + 1)
                if key == b'\t':
                    if now == 0: status = 'prev'
                    if now == 2: status = 'next'
                    break
                if key == b'S' or key == b'\x08':
                    if now == 1: dislike.add(BV); break
                    if now == 0: dislike.add(played.pop()) 
                    if now == 2: dislike.add(video.pop())
                if key == b'R':
                    try:
                        video = []; crawl()
                    except Exception as e: pass
                    with open('bilibili-videos.json', 'w', encoding='utf-8') as file:
                        json.dump(name, file, ensure_ascii=False, indent=4)
                    random.shuffle(video)
                    played, dislike = [], set()
                    BV = video.pop(); break
        if status == 'prev':
            if played: video.append(BV); BV = played.pop()
        if status == 'next':
            if not video:
                video = played[:]; played = []
                random.shuffle(video)
            if not BV in dislike: played.append(BV)
            BV = video.pop()
    except Exception as e:
        print(flush=True); os.system('cls')
        print(e, "\n播放失败,按 Enter 重试")
        while code := input(':-( '):
            try:
                exec(code)
            except Exception as err: print(err)

driver.quit()

::: :::warning[Warning] 别用,tmd bug 一堆
崩溃是正常的,重启一下就好了(? :::