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

如何用JavaScript编写函数访问网站填入姓名并获取点赞数?

实现方案:用Node.js + Puppeteer自动化获取网站数据

浏览器端JavaScript受同源策略限制,无法直接跨域操作其他网站的DOM,因此我们需要用Node.js环境搭配浏览器自动化工具来实现需求,这里推荐使用Puppeteer(Headless Chrome工具)。

步骤1:准备环境

  • 先安装Node.js(建议版本14及以上)
  • 初始化项目并安装Puppeteer:
    npm init -y
    npm install puppeteer
    

步骤2:编写核心函数

以下是完整实现代码,包含详细注释:

const puppeteer = require('puppeteer');

async function getLikeCount(username) {
  // 启动无头浏览器(headless: true表示不显示可视化窗口)
  const browser = await puppeteer.launch({ headless: true });
  try {
    // 打开新页面
    const page = await browser.newPage();
    // 访问目标网站,等待网络空闲确保页面加载完成
    await page.goto('https://xyz.com', { waitUntil: 'networkidle2' });

    // 找到姓名输入框并填入内容(需根据网站实际元素选择器替换)
    await page.type('input[name="username"]', username);

    // 提交表单(这里假设用按钮提交,也可用page.keyboard.press('Enter')模拟回车)
    await page.click('button[type="submit"]');

    // 等待结果区域加载(需替换为网站实际结果元素的选择器)
    await page.waitForSelector('.result-container', { timeout: 5000 });

    // 获取结果文本内容
    const resultText = await page.$eval('.result-container', el => el.textContent);

    // 用正则提取点赞数
    const likeMatch = resultText.match(/点赞数:(\d+)/);
    if (!likeMatch) {
      throw new Error('未匹配到点赞数数据');
    }
    const likeCount = likeMatch[1];

    // 输出目标日志
    console.log(`${username}有${likeCount}个点赞!`);
    return likeCount;
  } catch (error) {
    console.error('获取数据失败:', error.message);
  } finally {
    // 无论成功失败都关闭浏览器,避免资源泄漏
    await browser.close();
  }
}

// 调用示例
getLikeCount('张三');

关键注意事项

  • 元素选择器替换:代码中的input[name="username"]、button[type="submit"]、.result-container都是假设的选择器,你需要打开xyz.com的开发者工具(F12),定位到对应元素的真实选择器进行替换。
  • 等待机制:waitUntil: 'networkidle2'和waitForSelector是为了应对网络延迟,确保页面和目标元素完全加载后再执行操作。
  • 异常处理:通过try-catch-finally结构,保证即使出现错误也能正常关闭浏览器,避免残留进程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:42:21