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

Playwright如何断言页面中两个标题至少存在一个?

问题:如何用Playwright规范断言两个标题中至少一个可见?

我的页面上有两个标题,需要确保其中任意一个存在于页面中。我最初编写的代码仅检查第一个标题是否可见:

let heading = page.getByRole('heading', {name: 'MyFirstHeading'});
let heading2 = page.getByRole('heading', {name: 'MySecondHeading'});
await expect(heading).toBeVisible();

我尝试了以下try-catch方法并生效:

try {
    await expect(page.getByRole('heading', {name: 'MyFirstHeading'})).toBeVisible();
} catch (error) {
    await expect(page.getByRole('heading', {name: 'MySecondHeading'})).toBeVisible();
}

请问是否有更规范的Playwright逻辑断言方式实现该需求?


规范实现方式

Playwright的expect断言原生支持.or()方法,可直接实现“逻辑或”的断言逻辑,比try-catch更简洁且符合框架设计规范。

你可以这样编写代码:

const heading1 = page.getByRole('heading', { name: 'MyFirstHeading' });
const heading2 = page.getByRole('heading', { name: 'MySecondHeading' });

await expect(heading1).toBeVisible().or(expect(heading2).toBeVisible());

这段代码的逻辑是:只要heading1可见或者heading2可见,断言就会通过,无需手动捕获异常再做二次判断。

如果你的需求是判断元素是否存在(而非可见),也可以替换断言方法为.toBeAttached(),用法一致:

await expect(heading1).toBeAttached().or(expect(heading2).toBeAttached());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:20:23