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

Playwright to_have_values():构建正则断言任意列表中的指定元素

Playwright多选元素的正则断言优化

问题场景

我有一段Playwright代码用于为多选元素选择选项,想要用expect()结合正则表达式断言选中选项中存在匹配.*oranges的项,但目前的写法需要为列表每个元素提供正则,受列表长度和元素位置限制,无法适配不同长度和位置的选中列表(比如['fr-oranges']、['fr-apples', 'fr-oranges']等)。现有代码如下:

def test_list_regex(page: Page):
    page.goto("https://example.cypress.io/commands/actions")

    select2 = page.locator(".action-select-multiple")
    select2.select_option(['fr-apples', 'fr-oranges', 'fr-bananas'])
    expect(select2).to_have_values(['fr-apples', 'fr-oranges', 'fr-bananas'])
    # 不知道如何用expect()优雅验证'fr-oranges'是选中选项的一部分
    expect(select2).to_have_values([re.compile(".*"), re.compile(".*oranges"), re.compile(".*")])

解决方案

要实现不受列表长度和位置影响的正则断言,你可以利用to_have_values支持传入断言函数的特性,通过遍历所有选中值来检查是否存在匹配正则的项:

方法1:使用lambda函数结合expect()

这种方式完全符合Playwright的断言风格,直接在to_have_values中传入lambda函数,遍历选中值并验证是否存在匹配项:

import re
from playwright.sync_api import Page, expect

def test_list_regex(page: Page):
    page.goto("https://example.cypress.io/commands/actions")

    select2 = page.locator(".action-select-multiple")
    select2.select_option(['fr-apples', 'fr-oranges', 'fr-bananas'])
    
    # 断言存在匹配.*oranges的选中值,适配任意长度和位置
    expect(select2).to_have_values(lambda values: any(re.fullmatch(r".*oranges", val) for val in values))
  • 若只需检查值包含"oranges"(而非以它结尾),可将re.fullmatch替换为re.search(r"oranges", val);
  • any()函数会遍历所有选中值,只要有一个匹配正则就返回True,断言通过。

方法2:先获取值再断言

如果你更习惯直接操作选中值,也可以先获取多选元素的选中值列表,再用普通断言验证:

selected_values = select2.input_values()
assert any(re.fullmatch(r".*oranges", val) for val in selected_values)

这种方式同样不受列表长度和位置限制,逻辑与方法1一致,只是写法更偏向传统断言风格。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 23:50:10