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

Playwright C#中如何将多元素存入列表(类似Selenium findElements)

Playwright C# 获取多元素列表(类似Selenium findElements)

你遇到的strict模式错误,是因为Playwright的Locator默认要求匹配恰好一个元素才能执行操作,而你的定位器匹配了3个元素,直接操作就会触发报错。要实现类似Selenium findElements的效果,用以下方法:

方法1:使用AllAsync()(推荐异步方式)

Playwright提供AllAsync()方法,可直接获取所有匹配元素的定位器列表,和Selenium的findElements逻辑一致:

// 获取所有单选按钮的定位器列表
var radioButtons = await Page.Locator("div[id='basic'] ph-radio-button").AllAsync();

// 点击第一个单选按钮
await radioButtons[0].ClickAsync();

// 遍历所有按钮执行验证或操作
foreach (var button in radioButtons)
{
    // 示例:验证按钮是否可见
    bool isVisible = await button.IsVisibleAsync();
    // 其他操作如获取文本、断言等
}

方法2:使用All()(同步方式)

如果你用的是Playwright同步API,直接用All()方法:

var radioButtons = Page.Locator("div[id='basic'] ph-radio-button").All();
// 点击第一个按钮
radioButtons[0].Click();

关于Nth()的正确用法

你之前用Nth()仍报错,大概率是写法问题。正确的方式是给每个Nth()后的定位器单独赋值,确保每个定位器只匹配单个元素:

List<ILocator> buttons = new List<ILocator>();
buttons.Add(Page.Locator("div[id='basic'] ph-radio-button").Nth(0));
buttons.Add(Page.Locator("div[id='basic'] ph-radio-button").Nth(1));
buttons.Add(Page.Locator("div[id='basic'] ph-radio-button").Nth(2));

// 此时操作单个元素不会报错
await buttons[0].ClickAsync();

但显然AllAsync()更简洁,无需手动逐个指定索引。

关键说明

Playwright的Locator是惰性求值的,AllAsync()会立即查询页面并返回所有匹配元素的定位器集合,每个返回的定位器都严格对应单个元素,执行操作时不会触发strict模式错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:45:53