使用Selenium选择特定前缀href链接时的XPath语法错误排查
场景
我需要抓取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语句存在语法混淆:
- 你用了CSS选择器的
href^=语法,但却指定了By.XPATH——XPath不支持这种写法。 - 错误使用
starts-with函数,正确的XPath语法是starts-with(属性名, 匹配字符串),不是starts-with(@href="xxx")。 - 代码中的
"是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

