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

如何用puppeteer-cluster实现多页面动态传入不同搜索词

解决Puppeteer-Cluster动态生成Google搜索页面的问题

你的代码需要调整几个核心地方,才能实现按数组里的组合词分别打开页面搜索:

  1. 传递实际的搜索词对象给任务:原来你传的是索引,应该直接把数组里的每个对象传给cluster.execute,这样任务里能直接拿到对应的firstWord和scndWord。
  2. 用稳定选择器定位搜索框:你原来的选择器是基于页面结构的绝对路径,很容易失效,换成input[name="q"]这种基于name属性的选择器更可靠。
  3. 动态拼接搜索词:在任务里把firstWord和scndWord拼接成完整的搜索词,代替硬编码的'flower'。
  4. 生成唯一截图文件名:每个任务用不同的文件名,避免截图被覆盖,比如用搜索词或者索引命名。
  5. 优化搜索导航逻辑:输入完搜索词后按回车,然后等待页面导航完成,确保截图是搜索后的结果页。

修改后的完整代码:

const { Cluster } = require('puppeteer-cluster');

(async () => {
    const cluster = await Cluster.launch({
        concurrency: Cluster.CONCURRENCY_PAGE,
        maxConcurrency: 10,
        puppeteerOptions: {
            headless: false,
        },
    });

    cluster.on('taskerror', (err, data) => {
        console.error(`${(new Date()).toJSON()}  Error searching "${data.firstWord}${data.scndWord}": ${err.message}`);
    });

    const arr = [
        { firstWord: 'gaming ', scndWord: 'pc' },
        { firstWord: 'red ', scndWord: 'flower' }
    ];

    await cluster.task(async ({ page, data }) => {
        // 拼接完整搜索词
        const searchQuery = data.firstWord + data.scndWord;
        
        await page.goto('https://www.google.com/');
        
        // 用稳定选择器定位搜索框
        const searchBox = await page.$('input[name="q"]');
        await searchBox.focus();
        await page.keyboard.type(searchQuery);
        
        // 按回车触发搜索并等待导航完成
        await Promise.all([
            page.waitForNavigation(),
            page.keyboard.press('Enter')
        ]);
        
        // 生成唯一截图文件名
        await page.screenshot({ 
            path: `screenshot_${searchQuery.replace(/\s+/g, '_')}.png`, 
            fullPage: true 
        });
    });

    // 遍历数组,传递每个对象给集群任务
    for (const item of arr) {
        await cluster.execute(item);
    }

    // 等待所有任务完成后关闭集群
    await cluster.idle();
    await cluster.close();
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:05:21