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

使用Playwright获取所有th标签并校验表头值与顺序的方法

Playwright校验表格表头数量、文本、顺序实现方案

问题背景

我正在使用Playwright开展页面自动化测试,当前待测试页面包含如下表格:
待测试订阅表格

需求为校验表格thead下所有th列的数量、文本值是否准确,且排列顺序符合预期(表头需按顺序排列为Product、Price等指定字段)。
最初编写的代码存在逻辑冗余、选择器错误的问题,代码如下:

test('the table headings are in place and in the correct order', async ({
      page,
    }) => {
      log('looking for the table headings...');

      const tableThead = page.$$('table.subscriptions > thead > tr > th');

      const allThs = await page.$$eval(
        'table.subscriptions > thead > tr',
        (ths) => {
          return ths.map((th) => {
            const product = th.querySelector('th:nth-child(1)');
            const price = th.querySelector('th:nth-child(2)');
            const term = th.querySelector('th:nth-child(3)');
            const renewalDate = th.querySelector('th:nth-child(4)');
            const renewalAmount = th.querySelector('th:nth-child(5)');
            const renewalType = th.querySelector('th:nth-child(6)');
            const paymentType = th.querySelector('th:nth-child(6)');
            const address = th.querySelector('th:nth-child(7)');
            return {
              product,
              price,
              term,
              renewalDate,
              renewalAmount,
              renewalType,
              paymentType,
              address,
            };
          });
        }
      );

      log('taking a screenshot...');

      await tableThead.screenshot({
        path: 'screenshots/subscriptions/table/table-head.png',
      });
    });

运行他人提供的旧方案后得到异常结果:
旧方案运行结果

最优实现方案

核心逻辑是直接按DOM顺序提取所有表头的文本组成数组,和预定义的预期表头数组做全等断言,可一次性覆盖数量校验、文本值校验、排列顺序校验三个需求点,代码简洁可维护,同时修正原代码的选择器错误、方法调用错误。

实现代码

test('表格表头字段、数量、顺序符合预期', async ({ page }) => {
  log('定位表格表头...');
  // 定位表头行下所有th元素,使用Playwright推荐的locator定位方式,稳定性更高
  const headerThs = page.locator('table.subscriptions > thead > tr > th');
  // 按DOM顺序提取所有th的可见文本,返回数组
  const actualHeaderTexts = await headerThs.allTextContents();

  // 提前定义预期的表头值和顺序,可根据实际业务调整
  const expectedHeaderTexts = [
    'Product',
    'Price',
    'Term',
    'Renewal Date',
    'Renewal Amount',
    'Renewal Type',
    'Payment Type',
    'Address'
  ];

  // 一次断言同时校验三个规则:数组长度一致=列数正确、每个位置值相等=文本正确+顺序正确
  expect(actualHeaderTexts).toEqual(expectedHeaderTexts);

  log('截取表头截图...');
  await headerThs.screenshot({
    path: 'screenshots/subscriptions/table/table-head.png',
  });
});

原代码问题说明

  • 选择器逻辑冗余:$$eval定位到tr元素后再逐个按nth-child查找th,属于多余嵌套,可直接定位所有th元素
  • 定位错误:Payment Type字段错误使用了nth-child(6)选择器,和Renewal Type的选择器重复,会导致取值错误
  • 方法调用错误:page.$$返回的是元素句柄数组,无法直接调用screenshot方法,使用locator定位元素集合可直接调用截图方法
  • 可维护性差:逐个字段写选择器的方式,后续表头增减、顺序调整时需要修改大量选择器代码,使用数组对比的方式仅需修改预期表头数组即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:27:46