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

如何用Playwright随机选择动态表格中的行复选框?

实现Playwright随机选中动态表格行的复选框

表格中的集合(set)会持续动态变化,每次进入「Receiving Station」页面后,需要随机选中表格内某一行的checkbox(比如这次选set 2,下次选set 5)。你用Playwright Codegen生成了测试代码,但当前代码固定选中指定ID的复选框,下面是修改后的代码来实现随机选择功能:

原代码

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
  await page.goto('https://xxxxxx.com');
  await page.locator('#email').click();
  await page.locator('#email').fill('xxx@gmail.com');
  await page.locator('#password').press('CapsLock');
  await page.locator('#password').fill('xxx@123');
  await page.locator('#password').press('Enter');
  await page.getByRole('link', { name: 'Receiving Station' }).click();
  await page.locator('[id="\\32 778"]').check();
});

修改后的代码

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
  await page.goto('https://xxxxxx.com');
  await page.locator('#email').click();
  await page.locator('#email').fill('xxx@gmail.com');
  await page.locator('#password').press('CapsLock');
  await page.locator('#password').fill('xxx@123');
  await page.locator('#password').press('Enter');
  await page.getByRole('link', { name: 'Receiving Station' }).click();

  // 关键修改:实现随机选择复选框
  // 1. 定位表格内所有行的复选框,需根据实际页面调整选择器
  const checkboxes = page.locator('table tbody input[type="checkbox"]');
  // 2. 等待复选框加载完成,确保动态表格渲染完毕
  await checkboxes.waitFor();
  // 3. 获取当前页面所有复选框的数量
  const checkboxCount = await checkboxes.count();
  // 4. 生成0到总数-1之间的随机索引
  const randomIdx = Math.floor(Math.random() * checkboxCount);
  // 5. 根据随机索引选中对应复选框
  await checkboxes.nth(randomIdx).check();
});

注意事项

  • 调整复选框选择器:如果页面中表格行的复选框有专属class或其他特征,把table tbody input[type="checkbox"]替换成实际定位符,比如table tbody .row-checkbox。
  • 若表格加载较慢,可适当增加等待逻辑,确保能获取到正确的复选框数量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:57:28