You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Playwright中的TypeError: page.locator(...).toContainText不是函数

修复Playwright中"toContainText is not a function"错误

问题原因

<meta name="description"> 元素的描述内容存储在 content 属性中,而非元素的文本内容里。toContainText 方法仅适用于检查元素内部的可见文本(如<div>、<p>等标签的文本),无法用于验证属性值,因此会抛出该错误。

修复方案

你需要通过检查content属性的值来验证元描述,以下是两种可行的方法:

方法1:使用toHaveAttribute结合字符串包含匹配

直接断言元元素的content属性包含目标文本:

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(); 
    const MetaDescription = page.locator("//meta[@name='description']");
    // 使用expect.stringContaining检查属性值是否包含目标文本
    await expect(MetaDescription).toHaveAttribute(
        'content', 
        expect.stringContaining('Empower your organisation to function onshore and offshore as one enterprise by using our versatile range of services and regional service delivery')
    );
});

方法2:获取属性值后单独断言

先提取content属性的值,再用toContain验证:

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(); 
    const MetaDescription = page.locator("//meta[@name='description']");
    // 获取content属性值
    const metaContent = await MetaDescription.getAttribute('content');
    // 断言值包含目标文本
    await expect(metaContent).toContain('Empower your organisation to function onshore and offshore as one enterprise by using our versatile range of services and regional service delivery');
});

内容的提问来源于stack exchange,提问作者Sarah G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 01:52:23