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

Playwright如何验证输入框值包含指定内容?

解决Playwright断言Input值包含指定内容的问题

你当前代码报错的核心原因是to_have_value默认执行精确匹配,而你的Input实际值是123 456,和传入的123完全不匹配,因此触发断言失败。以下是三种可行的解决方式:

方法1:使用正则表达式匹配

Playwright的to_have_value支持传入正则表达式,只要值中包含目标字符串就会匹配成功:

import re

input_locator = 'input[id="edition"]'
expect(self.page.locator(input_locator).first).to_have_value(
    re.compile(r'123'), 
    timeout=20 * 1000
)

方法2:手动获取值后断言包含关系

先获取Input的实际值,再用Python原生的包含逻辑验证:

input_locator = 'input[id="edition"]'
# 获取元素的value属性值
actual_value = self.page.locator(input_locator).first.input_value()
# 断言目标字符串存在于实际值中
assert '123' in actual_value

方法3:自定义断言逻辑

通过to_pass方法自定义验证规则,适合更复杂的校验场景:

input_locator = 'input[id="edition"]'
expect(self.page.locator(input_locator).first).to_pass(
    lambda locator: '123' in locator.input_value(),
    timeout=20 * 1000,
    message="Input值未包含'123'"
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:35:24