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

Selenium JavascriptExecutor报错:无效或意外令牌,关联:nth-child选择器

问题分析与解决
  • 执行以下Selenium代码时抛出org.openqa.selenium.JavascriptException: javascript error: Invalid or unexpected token错误:
    js.executeScript("arguments[0].textContent=${value}", driver.findElement(By.cssSelector('div.stb-LazyChosenDropdown div.tiles div.input:nth-child(1)')))
    
  • 移除选择器中的:nth-child(1)后代码可正常运行。

问题根源

错误和(1)无关,真正问题是JavaScript字符串模板语法的误用:你在Java字符串中直接写了${value},但Java本身不会解析这个模板变量,会把它原封不动传给JavaScript执行器,导致JS引擎无法识别该语法,抛出无效令牌错误。

解决方法

方法1:Java字符串拼接传递值

将${value}替换为Java字符串拼接逻辑,示例:

String targetValue = "要设置的文本内容";
js.executeScript("arguments[0].textContent='" + targetValue + "'", driver.findElement(By.cssSelector("div.stb-LazyChosenDropdown div.tiles div.input:nth-child(1)")));

注意:如果targetValue包含单引号,需要手动转义,避免JS语法错误。

方法2:通过arguments传递参数(更安全)

利用arguments数组传递值,彻底避免字符串拼接的转义问题:

String targetValue = "要设置的文本内容";
js.executeScript("arguments[0].textContent = arguments[1];", 
    driver.findElement(By.cssSelector("div.stb-LazyChosenDropdown div.tiles div.input:nth-child(1)")),
    targetValue);

这种方式无需处理特殊字符,同时nth-child(1)选择器可正常使用。

方法3:使用String.format生成JS脚本

如果习惯模板写法,可借助Java的String.format生成合法的JS字符串:

String targetValue = "要设置的文本内容";
String jsScript = String.format("arguments[0].textContent='%s'", targetValue);
js.executeScript(jsScript, driver.findElement(By.cssSelector("div.stb-LazyChosenDropdown div.tiles div.input:nth-child(1)")));

同样需要注意对targetValue中的特殊字符进行转义。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:45:32