Playwright使用toHaveAttribute断言报错:Unsupported token '@xpath'求助
修复Playwright脚本中的选择器与断言错误
问题分析
- 选择器解析失败:你直接将XPath字符串传给
page.locator(),但Playwright默认把输入当作CSS选择器解析,无法识别@xpath语法,因此抛出Unsupported token "@xpath"错误。 - 断言逻辑错误:你试图用
toHaveAttribute验证title元素的文本内容,但该方法是用来校验元素属性值的;同时你断言的参数也有误,把目标文本当成了属性值,属性名也写错了。
修复方案
方案1:验证页面标题文本(推荐,这是页面标题验证的常规需求)
无需定位title元素,直接用Playwright提供的页面标题断言方法,或者定位元素后验证文本:
import { test, expect } from '@playwright/test'; test('Landing page', async ({ page }) => { await page.goto('https://www.unient.biz/'); await page.getByRole('button', { name: 'Accept All' }).click(); // 方法一:直接断言页面标题(最简洁) await expect(page).toHaveTitle('Unient | Your Versatile Partner for Better Offshoring'); // 方法二:定位title元素后验证文本内容 const titleElement = page.locator('title'); // 用CSS选择器定位唯一的title元素 await expect(titleElement).toHaveText('Unient | Your Versatile Partner for Better Offshoring'); });
方案2:若需验证title元素的xpath属性
需要明确指定使用XPath选择器,同时修正toHaveAttribute的参数:
import { test, expect } from '@playwright/test'; test('Landing page', async ({ page }) => { await page.goto('https://www.unient.biz/'); await page.getByRole('button', { name: 'Accept All' }).click(); // 用`xpath=`前缀告知Playwright使用XPath选择器 const titleElement = page.locator('xpath=/html/head/title[@xpath="1"]'); // 验证元素的xpath属性值为"1" await expect(titleElement).toHaveAttribute('xpath', '1'); });
关键提示
- Playwright的
locator()默认使用CSS选择器,若要使用XPath,需在选择器前添加xpath=前缀。 toHaveAttribute(attrName, attrValue)用于校验元素的属性值;toHaveText(text)用于校验元素的文本内容;expect(page).toHaveTitle(title)是验证页面标题的快捷方法。
内容的提问来源于stack exchange,提问作者Sarah G
相关产品推荐
相关产品推荐

