typescript - 在 Playwright 中无法定位具有全数字 id 属性的 <a> 元素('#56' 不是有效的选择器)
我想捕获并定位具有 id 属性的 <a> 元素。可能的属性:
- 角色
- 链接
- 标题
- 身份证
- 风格
- 点击
我可以按角色和名称来做,但无法按 id 或 onclick 来做。后两者在未来的工作中会很有用。
当我尝试点击通过角色和名称定位的定位器时,一切正常:
point56Button = this.page.getByRole('button', {
name: 'Pole 56',
exact: true,
});
但是如果用 id 做,我会得到错误:locator.click: DOMException: 无法在 'Document' 上执行 'querySelectorAll': '#56' 不是有效的选择器。
at query (<anonymous>:3329:41)
at <anonymous>:3339:7
at SelectorEvaluatorImpl._cached (<anonymous>:3116:20)
at SelectorEvaluatorImpl._queryCSS (<anonymous>:3326:17)
at SelectorEvaluatorImpl._querySimple (<anonymous>:3206:19)
at <anonymous>:3154:29
at SelectorEvaluatorImpl._cached (<anonymous>:3116:20)
at SelectorEvaluatorImpl.query (<anonymous>:3147:19)
at Object.query (<anonymous>:3361:44)
at <anonymous>:3319:21
网站代码:
<a role="button" href="#" title="Pole 56" id="56" style="width:104px;height:16px;top:611px;left:668px;text-align:Right;vertical-align:text-bottom;position:absolute;cursor:pointer;padding-top:71px;font-size:13px;color:black;" onclick="RunSubwizard('56',event);"></a>
我用来通过 id 定位元素的代码:
point56Button = this.page.locator('#56');
我想点击由id定位的元素
预期结果:打开向导
通过角色和名称定位元素有效,使用ID定位元素无效
答案#1
在我的情况下,这有效:
HTML 元素想要定位
<a role="button" href="#" title="Pole 56" id="56" style="width:104px;height:16px;cursor:pointer" onclick="RunSubwizard('56',event);"></a>
通过定位器进行
point56Button = this.page.locator('a[id="56"]');
答案#2
这与 Playwright 无关,尽管上下文是有用的。CSS 选择器错误在纯浏览器代码中表现出来:
document.querySelector("#56");
// => SyntaxError: Document.querySelector: '#56' is not a valid selector<a id="56"></a>处理全数字 ID 的一种变通方法是使用属性选择器:
console.log(document.querySelector('[id="56"]'));<a id="56"></a>如果不明显,Playwright 定位器将是 this.page.locator('a[id="56"]');,虽然 ID 应该是唯一的,所以 a 几乎肯定是不必要的。
相关:如何选择一个 ID 以数字开头的元素?
