import { chromium } from 'playwright'; (async () => { const browser = await chromium.launch({ headless: false }); const context = await browser.newContext(); const page = await context.newPage(); // 跳转到表格页面 await page.goto('https://example.com/table');
import { chromium } from 'playwright'; (async () => { const browser = await chromium.launch({ headless: false }); const context = await browser.newContext(); const page = await context.newPage(); // 跳转到表格页面 await page.goto('https://example.com/table');
// 正则表达式,用于验证日期格式 const dateRegex = /\d{4}-\d{2}-\d{2}/; // 获取所有表格行 const rows = await page.$$('div.table-row'); let foundDataCount = 0; // 循环遍历每个表格行 for (const row of rows) { // 获取日期、姓名、年龄单元格 const dateCell = await row.$('div:nth-child(1)'); const nameCell = await row.$('div:nth-child(2)'); const ageCell = await row.$('div:nth-child(3)');
// 如果单元格都存在,获取单元格的文本内容
if (dateCell && nameCell && ageCell) {
const [date, name, age] = await Promise.all([
dateCell.textContent(),
nameCell.textContent(),
ageCell.textContent(),
]);
// 判断是否为需要查找的数据
if (dateRegex.test(date) && name === data1.name && age === data1.age) {
foundDataCount++;
}
if (dateRegex.test(date) && name === data2.name && age === data2.age) {
foundDataCount++;
}
}
}
// 验证查找到的数据数量是否为2
expect(foundDataCount).toBe(2);
// 关闭浏览器
await browser.close();
})();
第11-13行:使用 waitForSelector 等待表格数据加载完成。
第20-23行:使用 XPath 定位每个单元格,以获取文本内容。
第29-32行:使用 Promise.all 一次性获取每个单元格的文本内容。
第35-39行:使用 textContent 属性获取单元格文本内容,以提高性能。
第6行和7行:由于页面中使用的是 div,因此需要修改选择器。此外,还需要注意使用 nth-child 选择器定位每个单元格。