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

Puppeteer查询选择器报错TypeError: selector.startsWith is not a function求助

解决Puppeteer中TypeError: selector.startsWith is not a function错误

错误原因

你在代码中调用page.focus(username)时,username是page.waitForSelector('#firstName')返回的ElementHandle对象,但page.focus()方法要求传入的是选择器字符串,而非DOM元素对象。当Puppeteer尝试把这个对象当作选择器处理时,调用startsWith方法自然会报错——因为对象没有这个字符串专属方法。

修复方案

有两种可行的修复方式:

方式一:直接传入选择器字符串给page.focus()

无需提前获取ElementHandle,直接把选择器传给page.focus即可:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({headless: false});
  const context = await browser.createIncognitoBrowserContext();
  if (context) {
    const page = await browser.newPage();

    await page.goto('https://accounts.google.com/signup/v2/webcreateaccount?biz=false&cc=TR&dsh=S-519439412%3A1682412535258329&flowEntry=SignUp');
  
    await page.setViewport({width: 1080, height: 1024});
    // 直接传入选择器字符串
    await page.focus('#firstName');
    await page.keyboard.type('test54');
  }
  // 关闭浏览器避免资源泄漏
  await browser.close();
})();

方式二:调用ElementHandle自身的focus()方法

如果已经获取到ElementHandle,直接调用该对象的focus方法,而非page.focus():

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({headless: false});
  const context = await browser.createIncognitoBrowserContext();
  if (context) {
    const page = await browser.newPage();

    await page.goto('https://accounts.google.com/signup/v2/webcreateaccount?biz=false&cc=TR&dsh=S-519439412%3A1682412535258329&flowEntry=SignUp');
  
    await page.setViewport({width: 1080, height: 1024});
    const username = await page.waitForSelector('#firstName');
    // 调用ElementHandle的focus方法
    await username.focus();
    await page.keyboard.type('test54');
  }
  await browser.close();
})();

额外提示

  • 你之前测试的page.$eval('#firstName', elem => elem.click())写法本身是正确的,报错大概率是因为其他地方存在类似page.focus的错误调用——把ElementHandle当作选择器传入。
  • 代码末尾建议添加await browser.close(),避免浏览器进程残留占用系统资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:15:09