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

全新安装Puppeteer后调用page.$报错TypeError: selector.startsWith is not a function

解决Puppeteer中page.$()抛出TypeError: selector.startsWith is not a function的问题

问题详情

  • 环境:Node.js v18.14.2,全新搭建的Puppeteer项目(执行npm init -y、npm install puppeteer、touch index.js完成初始化)
  • 出错代码:
const n = await page.$("button[data-test-component='StencilReactButton']")
  • 报错信息:TypeError: selector.startsWith is not a function,错误指向GetQueryHandler.js:51

可能原因

这个错误的核心是page.$()接收到的选择器参数不是字符串类型,虽然代码里写的是字符串,但可能存在以下情况:

  • 代码中存在变量覆盖,导致实际传入的选择器被改成了非字符串类型
  • Puppeteer版本与当前Node.js版本存在兼容性问题,导致参数处理逻辑异常

解决方案

你采用的替代方案是可行的,直接在浏览器上下文调用原生DOM方法:

// 注意修正原代码中的拼写错误:componet → component
let selector = "button[data-test-component='StencilReactButton']";
await page.evaluate((selector) => document.querySelector(selector).click(), selector);

另外可以尝试以下排查修复步骤:

  • 验证选择器类型:调用page.$()前添加console.log(typeof "button[data-test-component='StencilReactButton']"),确认输出为string
  • 更新Puppeteer:执行npm install puppeteer@latest,使用最新稳定版规避可能的版本兼容bug
  • 检查代码上下文:确认没有其他代码修改page对象的$方法,导致参数处理逻辑被篡改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:42:10