Playwright中toHaveAttribute校验Meta Keywords失败问题求助
问题:Playwright校验Meta Keywords失败但Meta Description成功的原因及解决方法
问题详情
需要用Playwright的toHaveAttribute方法验证网站的Meta Keywords,定位器为page.locator('[name="keywords"]'),测试步骤为:
- 进入页面源代码视图
- 定位Meta Keywords元素
- 校验
content属性的预期值与实际值是否匹配
但校验Meta Keywords时未通过,用相同方法校验Meta Description却能成功。
测试脚本
import { test, expect } from '@playwright/test'; test('test', async ({ page }) => { await page.goto('https://stage-unientwww.euwest01.umbraco.io/'); await page.getByLabel('User name').click(); await page.getByLabel('User name').fill('unienttest'); await page.getByLabel('Password').click(); await page.getByLabel('Password').fill('Unient1234'); await page.getByRole('button', { name: 'Log in' }).click(); await page.getByRole('button', { name: 'Accept All' }).click(); await page.getByRole('heading', { name: 'Your Versatile Partner for Better Offshoring' }).click({ button: 'right' }); await page.goto('view-source:https://stage-unientwww.euwest01.umbraco.io/'); const Keywords = page.locator('[name="keywords"]'); await expect(Keywords).toHaveAttribute('content','Unient, bpo company, outsource company, bpo company philippines, bpo outsource, one outsource, offshoring australia, outsourcing philippines, outsourced bpo, bpo companies.'); });
页面Meta元素代码
<head> <meta name="description" content="Empower your business to function onshore and offshore as one enterprise with Unient's versatile range of services and regional service delivery capabilities." <meta name="keywords" content="Unient, bpo company, outsource company, bpo company philippines, bpo outsource, one outsource, offshoring australia, outsourcing philippines, outsourced bpo, bpo companies" </head>
原因分析
- 预期值与实际值不匹配:测试脚本中预期的
content值末尾多了一个句号(bpo companies.),但页面实际的Meta Keywords的content值末尾没有句号(bpo companies),这是校验失败的直接原因。 - 不必要的源代码视图跳转:跳转到
view-source:页面是多余的,该页面以纯文本形式展示源码,并非标准DOM结构,定位器可能无法正确识别元素,Meta Description校验成功可能只是巧合。
解决方法
- 修正预期值:将预期的
content值末尾的句号去掉,与页面实际值保持一致。 - 移除源代码视图跳转:直接在登录后的目标页面定位Meta元素,无需跳转到源码视图。
修正后的测试脚本
import { test, expect } from '@playwright/test'; test('test', async ({ page }) => { await page.goto('https://stage-unientwww.euwest01.umbraco.io/'); await page.getByLabel('User name').fill('unienttest'); await page.getByLabel('Password').fill('Unient1234'); await page.getByRole('button', { name: 'Log in' }).click(); await page.getByRole('button', { name: 'Accept All' }).click(); // 直接在当前页面定位Meta Keywords元素 const keywordsMeta = page.locator('[name="keywords"]'); await expect(keywordsMeta).toHaveAttribute( 'content', 'Unient, bpo company, outsource company, bpo company philippines, bpo outsource, one outsource, offshoring australia, outsourcing philippines, outsourced bpo, bpo companies' ); });
内容的提问来源于stack exchange,提问作者Sarah G
相关产品推荐
相关产品推荐

