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

双变量拼接XPath表达式报错,单变量正常,求助排查

解决双变量构造XPath表达式的语法错误问题

你的代码报错是因为字符串拼接时引号嵌套处理错误,导致最终生成的XPath语法不合法。原代码里的""""+product+""""会让JS代码中的XPath出现重复双引号(比如contains(text(), ""Air Force 1 Low"")),而XPath要求字符串必须用单引号或成对的双引号包裹,这种重复引号会被判定为无效语法。

下面是两种可行的修改方案:

方案1:XPath用单引号包裹变量值(推荐)

利用Python的f-string简化拼接,同时让XPath使用单引号,避免和JS的字符串双引号冲突:

product = "Air Force 1 Low"
color = "White"

findJS = f"""
const $xOne = xp => document.evaluate(xp, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
$xOne('//*[contains(text(), "{product}")]/../following-sibling::p/a[contains(text(), "{color}")]').click();
"""

方案2:JS使用模板字符串构造XPath

用JS的模板字符串(反引号)来写XPath,避免引号嵌套混乱:

product = "Air Force 1 Low"
color = "White"

findJS = f"""
const $xOne = xp => document.evaluate(xp, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
const xpath = `//*[contains(text(), "{product}")]/../following-sibling::p/a[contains(text(), "{color}")]`;
$xOne(xpath).click();
"""

这两种方案都会生成语法合法的XPath表达式,解决报错问题。

内容的提问来源于stack exchange,提问作者Lukáš Čimo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:20:32