JavaScript使用Playwright时page.locator报非函数错误
根本原因
报错的核心原因是你本地安装的Playwright版本过于老旧。page.locator 是Playwright 1.14及以上版本才提供的API,你当前package.json里安装的是0.10.0版本——这是2020年发布的早期预览版本,根本没有内置locator相关方法,调用时自然会抛出「不是函数」的错误。
修复步骤
- 先卸载项目里的旧版本依赖,在终端执行:
npm uninstall playwright playwright-core
- 安装最新稳定版的Playwright相关包:
npm install playwright @playwright/test
- 安装对应版本的浏览器运行依赖:
npx playwright install
附带的代码问题修正
你的现有脚本还有两处逻辑问题,升级版本后也需要调整才能正常运行:
- 自定义的
delay是异步Promise方法,调用时必须加await,否则不会真的等待5秒,程序会直接执行完退出,正确写法是await delay(5000); - 脚本执行完成后没有关闭浏览器的逻辑,会导致Chromium进程后台残留,需要在逻辑末尾加
await browser.close(); - 你开头引入的
test、expect是Playwright测试运行器专用的API,单独写独立运行脚本时不需要引入,可以直接删掉那行代码。
修正后可直接运行的完整代码如下:
const playwright = require('playwright'); const delay = ms => new Promise(res => setTimeout(res, ms)); (async () => { const browser = await playwright.chromium.launch({ headless: false }); const context = await browser.newContext(); const page = await context.newPage(); await page.goto("https://stackoverflow.com/"); const locator = page.locator('text=About'); // 可通过count()方法验证定位是否生效 console.log('定位到的匹配元素数量:', await locator.count()); await delay(5000); await browser.close(); })();
内容的提问来源于stack exchange,提问作者Todd Baker
相关产品推荐
相关产品推荐

