全新安装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
相关产品推荐
相关产品推荐

