如何在Playwright中找到带有特定文本同级元素的<input>?
问题:Playwright定位自定义表单组件内的输入框失败
我有一个包含多个如下结构的自定义表单组件(已移除无关元素):
<ui-input label="First Name"> <div>First Name</div> <div> <input type="text" placeholder="" autocomplete="off"> </div> </ui-input>
我想通过Playwright在对应的输入框中填充文本,按照Playwright的理念,应该找到内部的<input>元素并执行await input.fill("Humbleton")。
我尝试了以下几种定位方式,但都无效:
page.getByRole('textbox', { name: 'First Name' }); page.getByText('First Name').locator('input'); page.getByLabel('First Name').locator('input'); page.getByText('First Name').getByRole('textbox'); page.getByLabel('First Name').getByRole('textbox');
我不想通过添加唯一属性+XPath的方式解决,觉得这不符合e2e测试、整洁代码及Playwright的理念。目前只能用page.keyboard.press('Tab')切换字段来填充,但这种方式不够健壮,也不够贴近真实用户操作。有没有符合Playwright风格的优雅解决方案?
符合Playwright风格的解决方案
1. 基于自定义组件属性链式定位
利用<ui-input>上的label属性先定位到组件,再查找内部的输入框:
await page.locator('ui-input[label="First Name"] input').fill('Humbleton');
或者用Playwright推荐的角色定位+链式查找,将<ui-input>识别为表单组(group角色):
await page.getByRole('group', { name: 'First Name' }).locator('input').fill('Humbleton');
2. 通过文本关联组件与输入框
利用hasText方法关联包含指定文本的<ui-input>组件,再定位内部输入框:
await page.locator('ui-input').hasText('First Name').locator('input').fill('Humbleton');
3. 优化组件可访问性(推荐)
从根源解决问题,让输入框和标签建立可访问性关联:给标签添加ID,输入框通过aria-labelledby绑定该ID:
<ui-input label="First Name"> <div id="first-name-label">First Name</div> <div> <input type="text" placeholder="" autocomplete="off" aria-labelledby="first-name-label"> </div> </ui-input>
完成后,就能直接用最符合Playwright理念的方式定位:
await page.getByRole('textbox', { name: 'First Name' }).fill('Humbleton');
这种方式依赖Web可访问性标准,既符合Playwright的设计思路,也让组件对屏幕阅读器更友好。
内容的提问来源于stack exchange,提问作者Martin Drozdik
相关产品推荐
相关产品推荐

