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

使用Selenium选择特定前缀href链接时的XPath语法错误排查

问题:XPath语法错误导致Selenium无法定位活动链接

场景

我需要抓取Bandsintown麦迪逊市指定日期(2023年4月8日-9日)页面中,所有以https://www.bandsintown.com/e开头的活动链接,目标链接示例:

https://www.bandsintown.com/e/1027653913-orquesta-salsoul-del-mad-at-the-bur-oak?came_from=253&utm_medium=web&utm_source=city_page&utm_campaign=event

尝试的代码及错误

尝试1:未闭合括号的XPath

find_href = driver.find_element(By.XPATH,'a[href^="https://www.bandsintown.com/e"')

报错信息:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression a[href^="https://www.bandsintown.com/e" because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string 'a[href^="https://www.bandsintown.com/e"' is not a valid XPath expression.

尝试2:错误使用starts-with的XPath

find_href = driver.find_element(By.XPATH,'a[starts-with(@href="https://www.bandsintown.com/e")]')

尝试3:补充闭合括号后仍报错

find_href = driver.find_element(By.XPATH,'a[href^="https://www.bandsintown.com/e"]')

报错信息:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression a[href^="https://www.bandsintown.com/e"] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string 'a[href^="https://www.bandsintown.com/e"]' is not a valid XPath expression.

问题核心及解决方法

你的XPath语句存在语法混淆:

  1. 你用了CSS选择器的href^=语法,但却指定了By.XPATH——XPath不支持这种写法。
  2. 错误使用starts-with函数,正确的XPath语法是starts-with(属性名, 匹配字符串),不是starts-with(@href="xxx")。
  3. 代码中的"是HTML转义字符,直接用引号包裹字符串即可,无需转义。

正确写法一:使用XPath的starts-with函数

find_href = driver.find_element(By.XPATH,'//a[starts-with(@href, "https://www.bandsintown.com/e")]')

正确写法二:改用CSS选择器(保留href^=语法)

find_href = driver.find_element(By.CSS_SELECTOR,'a[href^="https://www.bandsintown.com/e"]')

如果要抓取所有符合条件的链接,建议用find_elements(复数形式)获取列表:

# XPath方式
all_links = driver.find_elements(By.XPATH,'//a[starts-with(@href, "https://www.bandsintown.com/e")]')
# CSS选择器方式
all_links = driver.find_elements(By.CSS_SELECTOR,'a[href^="https://www.bandsintown.com/e"]')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:47:03