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

Puppeteer中使用函数参数作为CSS选择器时遇未定义错误

问题分析与修复方案

你遇到的ReferenceError: css is not defined错误,核心原因是**page.evaluate()的回调函数运行在浏览器的上下文环境中,无法直接访问Node.js环境里的变量**。你在FindCandidate函数里定义的css参数属于Node.js上下文,直接在evaluate里用css的话,浏览器环境根本不知道这个变量是什么。


修复方法

要把Node.js里的变量传递到浏览器上下文,你需要在page.evaluate()的第二个参数位置传入变量,然后在回调函数里接收它:

async function FindCandidate(css) {
  let candidate1 = await page.evaluate( (selector) => document.querySelector(selector).innerText, css);
  console.log(candidate1);
}

这里的关键变化:

  • 给page.evaluate()的回调函数添加参数selector,用来接收外部传入的css变量
  • 在page.evaluate()的第二个参数位置传入css,这样Node.js会把这个变量的值传递到浏览器上下文里

另外,为了让代码更健壮,建议加上错误处理,避免因为选择器找不到元素导致程序崩溃:

async function FindCandidate(css) {
  try {
    let candidate1 = await page.evaluate( (selector) => {
      const element = document.querySelector(selector);
      return element ? element.innerText : "Element not found";
    }, css);
    console.log(candidate1);
  } catch(err) {
    console.error("Error finding candidate:", err);
  }
}

完整修复后的代码

const { email, password } = require('./config.json');
const { NS, ES ,SS ,NI, WW, EW ,NTW, CUML, DU, HNY, WY, SY, NM, SM, MER, MID, DN, LLR, SW, STAF, BIRM, CD, SOM, DGW, BNO, BS, HIOW, CSN, BH, ESX, SSX, K, NL, EL, WL, CL } = require('./regions.json');
const { selector1, selector2 } = require('./selectors.json');
const puppeteer = require('puppeteer');

(async () => {
  //New Session
  const browser = await puppeteer.launch({headless: false, ignoreHTTPSErrors: true})
  const page = await browser.newPage()

  //Defining Login Function
  async function Login() {
    await page.goto('https://www.respublica.co/login');
    await page.type('input[type="email"]', email);
    await page.type('input[type="password"]', password);
    await page.click('button');
    await page.waitForNavigation();
    console.log('Succesfully Logged In as:', page.url());
  }

  //Defining Navigation Function
  async function Navigate(region) {
    await page.goto(region);
    console.log('Navigated to', page.url());
    await page.waitForSelector('[style="position: absolute; box-sizing: border-box; z-index: 104; height: 300px; top: 0px; overflow-y: scroll; border-radius: 0px; width: 478.156px; left: 0px;"]');
  }

  //Defining Scroll Function
  async function Scroll() {
    for (let step = 0; step < 5; step++) {
      await page.click('[style="position: absolute; box-sizing: border-box; z-index: 104; height: 300px; top: 0px; overflow-y: scroll; border-radius: 0px; width: 478.156px; left: 0px;"]');
      await page.waitForTimeout(500);
      await page.keyboard.press('Space');
    }
  }

  //Defining Scrape Candidate Function (Fixed Version)
  async function FindCandidate(css) {
    try {
      let candidate1 = await page.evaluate( (selector) => {
        const element = document.querySelector(selector);
        return element ? element.innerText : "Target element not found";
      }, css);
      console.log(candidate1);
    } catch(err) {
      console.error("Failed to fetch candidate:", err);
    }
  }

  //Run this code
  try{
    await Login()
  } catch(err){
    console.log("Failed to log in");
  }
  await Navigate(SM)
  await Scroll()
  await FindCandidate('.entry-1[style="box-sizing: border-box; float: left; position: relative; z-index: 104; height: 84.25px; width: 478.156px; border-top-style: none; border-left-style: none; display: block;"]')
})();

内容的提问来源于stack exchange,提问作者George.M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:39:16