You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python+Selenium开发Spotify自动听歌脚本时XPath语法错误求助

解决Spotify自动播放脚本的Selenium XPath错误

核心错误原因

你遇到的InvalidSelectorException是因为XPath语法错误://[@id="main"] 缺少节点匹配符,正确写法应为 //*[@id="main"](*表示匹配任意类型节点)。

修正后的关键代码

将报错的播放按钮定位代码替换为:

# 等待播放按钮可点击并执行点击
play_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//*[@id="main"]/div/div[2]/div[3]/div[1]/div[2]/div[2]/div/div/div[2]/main/section/div[3]/div/div[1]/button'))
)
play_button.click()

完整优化后的脚本

为提升稳定性和可维护性,对脚本做以下优化:

  1. 替换过时的find_element_by_xpath方法,使用Selenium 4推荐的标准语法
  2. 用WebDriverWait替代硬编码sleep,等待元素加载完成
  3. 用更简洁稳定的定位方式替代冗长XPath
  4. 修复搜索导航栏的XPath错误(移除占位符)

优化后的代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep 

# 初始化浏览器
driver = webdriver.Chrome("C:\chromedriver\chromedriver.exe")
driver.get("https://accounts.spotify.com/en/login")

# 登录操作
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "login-username"))).send_keys("你的邮箱")
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "login-password"))).send_keys("你的密码")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "login-button"))).click()

# 跳过引导页面
sleep(2)
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="root"]/div/div[2]/div/div/button[2]/p'))).click()

# 进入搜索页面
WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="main"]/div/div[2]/nav/div[1]/ul/li[2]/a/span'))).click()

# 搜索歌曲
search_input = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="main"]/div/div[2]/div[1]/header/div[3]/div/div/form/input')))
search_input.send_keys("Nawy Midnight Dream")
sleep(2)

# 点击搜索结果中的歌曲
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="searchPage"]/div/div/section[1]/div[2]/div/div/div/div[2]/a/div'))).click()

# 点击播放按钮(用更稳定的CSS选择器定位)
play_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[aria-label="Play"]'))
)
play_button.click()

# 等待播放后退出
sleep(6)
driver.quit()

额外说明

  • 冗长XPath易因页面结构变化失效,推荐用元素的aria-label、id等属性定位,比如播放按钮用button[aria-label="Play"]比长XPath更可靠
  • 登录后若出现人机验证,需手动处理或添加对应解决方案
  • 确保ChromeDriver版本与你的Chrome浏览器版本匹配

内容的提问来源于stack exchange,提问作者ANGROD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:06:36