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

Playwright严格模式违规求助:Locator匹配多个Statements按钮

解决Playwright中定位多个元素的Strict Mode错误

错误原因

你使用page.getByRole('button', { name: 'Statements' })定位按钮时,页面上存在两个完全匹配的按钮元素,而Playwright默认的严格模式要求定位器必须唯一匹配一个元素,因此触发了报错。从错误信息可以看到,两个按钮分别归属#lp_line_6_a11y_queue和#lp_line_6两个父容器。

解决方案

以下是几种直接可行的修复方式:

方法1:通过父元素缩小定位范围

利用已知的父元素ID,精准定位目标按钮。比如你要点击#lp_line_6下的按钮,代码修改为:

await page.locator('#lp_line_6').getByRole('button', { name: 'Statements' }).click();

若目标是另一个按钮,将父元素ID替换为#lp_line_6_a11y_queue即可。

方法2:指定匹配元素的顺序

如果明确要点击第几个匹配元素,可使用first()或nth()方法:

// 点击第一个匹配的按钮
await page.getByRole('button', { name: 'Statements' }).first().click();

// 点击第二个匹配的按钮(nth从0开始计数)
await page.getByRole('button', { name: 'Statements' }).nth(1).click();

方法3:关闭严格模式(不推荐)

若暂时无法区分元素,可临时关闭严格模式,但此方法存在点错元素的风险,仅作为应急方案:

await page.getByRole('button', { name: 'Statements' }).click({ strict: false });

修改后的完整测试代码示例

以方法1为例,调整后的测试代码如下:

test('test', async ({ page }) => {
  await page.goto('https://www.test.com');    
  await page.getByPlaceholder('Section tag #1').click();
  await page.getByPlaceholder('Section tag #1').press('Control+a');
  await page.getByPlaceholder('Section tag #1').fill('inapptest');

  await page.getByRole('button', { name: 'UPDATE' }).click();
  await page.getByRole('button', { name: 'Message us' }).click();
  await page.getByPlaceholder('Enter text here').click();
  await page.getByPlaceholder('Enter text here').fill('hi');

  await page.getByPlaceholder('Enter text here').press('Enter');  
  // 精准定位目标按钮
  await page.locator('#lp_line_6').getByRole('button', { name: 'Statements' }).click();
  await page.getByRole('button', { name: 'Get statements' }).click();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:17:11