首页 > 解决方案 > 未捕获的 DOMException:无法在“CommandLineAPI”上执行“$”:不是有效的选择器

问题描述

我正在使用 selenium 为我的网页编写自动化 UI 测试。我正在测试的网页上有一个元素:

<&lt input type="checkbox" id="screening_questions[0].multiple_choice[0]-dealbreakerField" value="on" style="position: absolute; cursor: inherit; pointer-events: all; opacity: 0; width: 100%; height: 100%; z-index: 2; left: 0px; box-sizing: border-box; padding: 0px; margin: 0px;>

由于该元素具有 id 属性,因此我尝试使用其 id 值来定位它,但它不起作用。

如果我在 chrome 控制台中搜索该元素:

$('#screening_questions[0].multiple_choice[0]-dealbreakerField')

我得到了异常:未捕获的 DOMException:

Failed to execute '$' on 'CommandLineAPI': '#screening_questions[0].multiple_choice[0]-dealbreakerField' is not a valid selector.

我认为根据它的 id 值定位它会很简单。你能建议这里有什么问题吗?

标签: seleniumdomselenium-webdriverxpathcss-selectors

解决方案


此错误消息...

Failed to execute '$' on 'CommandLineAPI': '#screening_questions[0].multiple_choice[0]-dealbreakerField' is not a valid selector.

...暗示您采用的Locator Strategy不是有效的选择器

根据您共享的HTML ,所需元素是一个带有属性的<input>标签as并且要使用您必须转义字符的属性,您可以使用以下任一选项:typecheckboxid.

  • 选择器

    "input[id=\"screening_questions[0].multiple_choice[0]-dealbreakerField\"][type='checkbox']"
    
  • 路径

    "//input[@id=\"screening_questions[0].multiple_choice[0]-dealbreakerField\"][@type='checkbox']"
    

推荐阅读