无法运行Playwright官方入门指南「编写断言」示例问题求助
问题根因
toHaveTitle传入字符串时默认执行精确匹配,当前Playwright官网实际标题包含前缀描述,仅用'Playwright'作为参数无法匹配,你修改为正则匹配包含逻辑是正确的。- 严格模式报错是因为当前Playwright官网首页存在2个文本为「Get Started」的可点击元素(首屏主按钮、顶部导航栏按钮),
text=Get Started选择器会同时匹配到2个元素,触发Playwright默认的严格模式校验。 - 后续修改XPath后超时,是因为
text()="Get Started"为精确匹配文本节点,实际按钮文本前后存在空格、换行符,无法匹配到对应元素导致等待超时。
正确解决方法
无需修改为复杂的XPath写法,直接使用Playwright内置的first()方法指定取第一个匹配元素即可,修改后完整代码如下:
// 02_writing_assertions.spec.js const { test, expect } = require('@playwright/test'); test('my test', async ({ page }) => { await page.goto('https://playwright.dev/'); // Expect a title "to contain" a substring. await expect(page).toHaveTitle(/Playwright/); // 选择第一个匹配的Get Started元素做属性断言 const getStartedBtn = page.locator('text=Get Started').first(); await expect(getStartedBtn).toHaveAttribute('href', '/docs/intro'); // Expect an element "to be visible". await expect(page.locator('text=Learn more')).toBeVisible(); // 点击同一个第一个匹配的按钮 await getStartedBtn.click(); // Expect some text to be visible on the page. await expect(page.locator('text=System requirements')).toBeVisible(); // Compare screenshot with a stored reference. expect(await page.screenshot()).toMatchSnapshot('get-started.png'); });
如果需要更精准的定位避免误匹配,也可以通过父元素限定选择范围,比如仅匹配首屏区域的按钮:
const getStartedBtn = page.locator('.hero-section >> text=Get Started');
内容的提问来源于stack exchange,提问作者Deacon
相关产品推荐
相关产品推荐

