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

Playwright使用name选择器报错,如何按Id/Name定位元素?

在Playwright中按ID或Name定位元素的正确方式

你遇到的错误是因为Playwright不支持name=这类旧式选择器语法,它只遵循标准的CSS选择器或XPath规则,下面是正确的定位方法:

按Name定位元素

  • 使用CSS选择器:
    playwright.$('[name="startcreateddate"]')
    
  • 使用XPath:
    playwright.$('//*[@name="startcreateddate"]')
    

按ID定位元素

  • 使用CSS选择器(两种写法都有效,推荐带#的规范写法):
    // 规范写法
    playwright.$('#startcreateddate')
    // 简写(仅当ID值不包含特殊字符时可用)
    playwright.$('startcreateddate')
    
  • 使用XPath:
    playwright.$('//*[@id="startcreateddate"]')
    

额外说明

Playwright官方推荐优先使用CSS选择器,因为它性能更优,也更契合现代前端的选择器标准。如果是在Playwright测试框架中使用page对象进行定位,写法类似:page.locator('[name="startcreateddate"]')。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 16:07:04