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

Node.js异步函数联动问题求助:Puppeteer与Google Sheets API数据异常

Node.js脚本问题解决:Puppeteer爬取+Google Sheets写入异常

问题根源分析

1. ProtocolError报错原因

调用scrapeProduct()时未传入必填的url参数,导致page.goto(url)中的url为undefined,触发页面导航参数错误。同时代码存在变量名大小写不一致问题:scrapeProduct函数内定义的是grablinks(小写l),但返回的却是grabLinks(大写L),直接导致函数返回undefined。

2. 异步执行顺序问题

你的推测方向正确,但当前代码中gsrun已用await等待scrapeProduct完成,顺序问题并非核心,核心是上述参数和变量名错误。

修复后的完整代码

const puppeteer = require('puppeteer')
const { google } = require('googleapis')
// 填写你的credentials文件路径
const credentials = require('./your-credentials-file.json')

async function scrapeProduct(url) {
    const browser = await puppeteer.launch({
        headless: false
    });
    
    const page = await browser.newPage();
    // 传入有效的目标网页url
    await page.goto(url);

    // 替换为你的链接抓取逻辑,示例:获取所有a标签的href
    const grabLinks = await page.evaluate(() => {
        return Array.from(document.querySelectorAll('a')).map(a => [a.href]);
    }); 

    await browser.close();
    
    // 统一变量名,确保返回正确结果
    return grabLinks;    
}

const client = new google.auth.JWT(
    credentials.client_email, 
    null, 
    credentials.private_key, 
    ['https://www.googleapis.com/auth/spreadsheets']
);

// 将回调转为async/await风格,统一异步逻辑
async function authorizeAndRun() {
    try {
        await client.authorize();
        console.log('Connected!');
        await gsrun(client);
    } catch (err) {
        console.log(err);
    }
}

async function gsrun(cl){
    const gsapi = google.sheets({version: 'v4', auth: cl});
    // 传入目标网页url
    const grabLinks = await scrapeProduct('https://your-target-url.com');
    const updateOptions = {
        // 填写你的谷歌表格ID
        spreadsheetId: 'your-spreadsheet-id',
        // 填写要写入的单元格范围,比如'Sheet1!A1'
        range: 'Sheet1!A1',
        valueInputOption: 'USER_ENTERED',
        resource: { values: grabLinks }
    };

    let res = await gsapi.spreadsheets.values.update(updateOptions);
    console.log('数据写入完成:', res.data);
}

// 启动脚本执行
authorizeAndRun();

关键修复点

  • 给scrapeProduct传入有效目标URL,解决Page.navigate参数错误
  • 统一变量名grablinks为grabLinks,确保函数正确返回抓取结果
  • 将client.authorize的回调风格改为async/await,让异步逻辑更清晰
  • 补充Google Sheets必填配置项提示(表格ID、写入范围)
  • 在page.evaluate中补充示例抓取逻辑,可替换为自身需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:40:26