使用playwright写
时间: 2025-06-30 07:10:07 浏览: 8
在 Playwright 中,我们可以使用其强大的 API 来自动化浏览器操作。你提到的需求是:
1. 检查页面中所有元素的 `id` 是否都变更为输入框中指定的值。
2. 检查表格是否只有一行,并且该行的 ID 与输入框中的值一致。
以下是使用 **Playwright (Node.js)** 实现的完整示例代码。
---
### ✅ 使用 Playwright 编写的测试脚本
```javascript
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch({ headless: false }); // 设置为 true 可无头运行
const page = await browser.newPage();
await page.goto('http://your-test-page.com'); // 替换为你实际的测试页面地址
// 获取输入框中的值
const inputId = await page.inputValue('#id_input'); // 假设输入框的 selector 是 #id_input
// 获取页面上所有具有 id 属性的元素并检查它们的 id 是否等于 inputId
const elementsWithId = await page.$$('[id]');
for (const element of elementsWithId) {
const id = await element.getAttribute('id');
if (id !== inputId) {
throw new Error(`Element with ID '${id}' does not match expected ID '${inputId}'`);
}
}
console.log('✅ All elements have the correct ID.');
// 检查表格是否只有一行,并且该行的 ID 等于输入框的值
const tableSelector = '#table_id'; // 替换为你的表格选择器
const rows = await page.$$(`${tableSelector} tbody tr`);
if (rows.length !== 1) {
throw new Error(`Expected exactly one row in the table, but found ${rows.length}`);
}
const firstRowId = await rows[0].innerText(); // 假设整行内容就是 id,也可以改为 td:first-child
if (!firstRowId.trim().startsWith(inputId)) {
throw new Error(`Row ID '${firstRowId.trim()}' does not match expected ID '${inputId}'`);
}
console.log('✅ Table has exactly one row and matches the expected ID.');
await browser.close();
})();
```
---
### 🔍 代码说明:
- `page.inputValue('#id_input')`: 获取输入框的值。
- `page.$$('[id]')`: 获取页面中所有有 `id` 属性的元素。
- `element.getAttribute('id')`: 获取每个元素的 `id` 属性值。
- `page.$$(tableSelector + ' tbody tr')`: 获取表格中所有的行。
- `rows.length === 1`: 验证是否只有一行。
- `rows[0].innerText()`:获取第一行的内容(你可以根据实际情况改成读取某个单元格)。
---
### 📦 安装 Playwright(Node.js)
确保你已经安装了 Node.js 和 npm,然后运行:
```bash
npm init playwright@latest
# 或者单独安装
npm install playwright
```
---
###
阅读全文
相关推荐


















