Python Selenium实现SoundCloud自动播放器的异常处理问题
解决方案:SoundCloud自动播放器修正代码
直接上能解决你问题的代码,关键改进点在后面说明:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time # 初始化浏览器,可替换为Firefox等其他驱动 driver = webdriver.Chrome() # 替换成你要播放的SoundCloud曲目/页面URL driver.get("https://soundcloud.com/your-target-track-url") def handle_cookie_popup(): try: # 最多等待10秒,直到Cookie同意按钮可点击 accept_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler")) ) accept_btn.click() print("Cookie同意按钮已点击") except: # 未检测到弹窗时直接跳过,不中断程序 print("无Cookie弹窗,跳过处理") # 首次加载页面时处理Cookie handle_cookie_popup() # 按下空格键开始播放 driver.find_element(By.TAG_NAME, "body").send_keys(Keys.SPACE) print("已开始播放") # 循环执行:等待60秒 → 刷新页面 → 处理Cookie → 重新播放 while True: time.sleep(60) driver.refresh() print("页面已刷新") handle_cookie_popup() # 等待页面加载完成再操作,避免按键无效 WebDriverWait(driver, 15).until( EC.presence_of_element_located((By.TAG_NAME, "body")) ) driver.find_element(By.TAG_NAME, "body").send_keys(Keys.SPACE) print("已恢复播放")
关键改进说明
修复try-except语法错误:
你之前的错误是try块没有对应的except/finally分支,现在把Cookie处理封装成函数,用try-except捕获“找不到按钮”的异常,直接跳过,确保程序不会中断。解决刷新后无弹窗导致的报错:
每次刷新页面后都会调用handle_cookie_popup(),函数会自动检测弹窗是否存在:有就点击,没有就跳过,不会因为弹窗不存在而抛出错误。提升操作稳定性:
- 用
WebDriverWait等待元素加载,替代直接find_element,避免页面未加载完成就执行操作导致的无效点击/按键。 - 使用按钮ID
onetrust-accept-btn-handler定位Cookie同意按钮,比文本匹配更可靠(SoundCloud的Cookie按钮通常用这个固定ID)。
- 用
循环逻辑完善:
用while True实现无限循环播放,如果你需要固定次数,可以改成for i in range(你的次数)的形式。
内容的提问来源于stack exchange,提问作者Ryo Pas Dans Street Fighter
相关产品推荐
相关产品推荐

