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

Playwright TypeScript中POM模式列排序失效,无法获取列值

排查Playwright获取表格列值返回空列表的问题

我要获取表格指定列(如column1、column2)的值并验证排序,但运行代码时allValues返回空列表,无法正确定位列值,相关代码与HTML结构如下:

HTML结构

<div role="gridcell" aria-colindex="1">
 <div> value 1 </div>
</div>
<div role="gridcell" aria-colindex="1">
 <div> value 2 </div>
</div>
<!-- 更多行... -->

测试代码(测试文件)

test("排序列数据", async ({ page }) => {
  const sortColumn = new SortColumns(page, "1");
  const columnValues = await sortColumn.getColumnValues();
  console.log(columnValues);
  const sortedNames = [...columnValues].sort();
  expect(columnValues).toEqual(sortedNames);
});

SortColumns类代码(sort-columns.ts)

import { type Locator, type Page } from "@playwright/test";

export class SortColumns {
 columnValue: Locator;
 page: Page;

 constructor(page: Page, element: string) {
   this.page = page;
   this.columnValue = page.locator(`[role=aria-colindex]`, { hasText: element });
   console.log("test: " + this.columnValue);
 }

 async getColumnValues() {
  const allValues = await this.columnValue.allInnerTexts();
  console.log(allValues);
  return allValues.slice(1); // 移除表头
 }
}

错误排查与修复

核心错误点:

  1. 定位器语法完全错误:
    原代码中的[role=aria-colindex]不符合HTML结构,单元格的role属性值是gridcell,aria-colindex是独立属性,正确定位需同时匹配这两个属性。
  2. 多余的hasText过滤条件:
    构造函数传入的element是列索引(如"1"),但单元格内文本是value 1这类内容,{ hasText: element }会过滤掉所有目标元素,导致找不到任何结果。
  3. 不必要的slice(1):
    从提供的HTML看没有表头行,slice(1)会移除第一个有效数据值,需确认存在表头后再保留该逻辑。

修复后的SortColumns类代码:

import { type Locator, type Page } from "@playwright/test";

export class SortColumns {
 columnValue: Locator;
 page: Page;

 constructor(page: Page, columnIndex: string) {
   this.page = page;
   // 正确定位指定aria-colindex的gridcell元素
   this.columnValue = page.locator(`[role="gridcell"][aria-colindex="${columnIndex}"]`);
 }

 async getColumnValues() {
  // 等待元素加载完成,避免动态渲染导致的空列表
  await this.columnValue.waitFor();
  // 获取所有单元格文本并清理前后空格
  const allValues = await this.columnValue.allInnerTexts();
  // 若存在表头,可添加.slice(1)移除第一行
  return allValues.map(val => val.trim());
 }
}

额外优化建议:

  • 若表格为动态加载,需在测试开头添加等待数据渲染完成的逻辑(如等待某个加载状态消失)
  • 可通过locator.filter()方法更灵活地筛选元素,避免硬编码属性值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:45:11