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

Playwright .NET NUnit:嵌套Div内单选框定位多元素匹配问题排查

解决Playwright定位单选框的严格模式违规问题

问题原因

原代码的定位逻辑未精确限定在Question2的容器范围内,导致Playwright匹配到多个符合条件的元素,触发严格模式错误。

可行解决方案

方案1:通过问题标签定位父容器后选择Yes选项

await page
    // 定位Question2的文本标签
    .Locator("label", new() { HasText = "Question 2 (Help find me and tick yes)" })
    // 回到父级div容器
    .Locator("xpath=..")
    // 定位到容器内的yes-no组件
    .Locator("app-yes-no")
    // 找到组件内的Yes标签
    .Locator("label", new() { HasText = "Yes" })
    // 点击单选框对应的span
    .Locator("span.radioButton")
    .ClickAsync();

方案2:使用Filter的Has条件精确锁定容器

await page
    // 筛选包含Question2标签的div容器
    .Locator("div")
    .Filter(new() { 
        Has = page.Locator("label", new() { HasText = "Question 2 (Help find me and tick yes)" }) 
    })
    // 定位到目标组件内的Yes标签
    .Locator("app-yes-no label", new() { HasText = "Yes" })
    .Locator("span.radioButton")
    .ClickAsync();

方案3:直接操作单选框Input(推荐)

使用Playwright专门的CheckAsync方法勾选单选框,比点击样式元素更可靠:

await page
    .Locator("div")
    .Filter(new() { 
        Has = page.Locator("label", new() { HasText = "Question 2 (Help find me and tick yes)" }) 
    })
    // 直接定位Yes选项对应的单选框input
    .Locator("app-yes-no label:has-text('Yes') input[type='radio']")
    .CheckAsync();

内容的提问来源于stack exchange,提问作者sam.tldr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 18:03:12