使用Node.js和Cheerio爬取百度搜索结果并提取相关信息

使用Node.js和Cheerio爬取百度搜索结果并提取相关信息

一、背景介绍

随着互联网的发展,网络爬虫技术变得越来越重要。本文将介绍如何使用Node.js和Cheerio库从百度搜索结果中抓取指定关键词的相关网页链接,并进一步提取这些网页的内容。通过这种方式,我们可以自动收集大量信息,用于后续的数据分析或知识整理。

二、技术栈

Node.js: 用于编写后端服务的应用程序环境。
Cheerio: 一个快速、灵活且健壮的HTML解析器,类似于jQuery,用于处理HTML文档。
Axios: 用于发起HTTP请求。
modelfusion: 一个假设存在的库,用于调用AI模型进行文本处理。

三、代码实现

1. 安装依赖

首先确保安装了所需的依赖包:

npm install cheerio axios modelfusion

2. 爬取百度搜索结果

async function crawlPages(keyword, result_num) {
  const keywordEncoded = encodeURIComponent(keyword);
  const baseUrl = "http://www.baidu.com/s?wd=" + keywordEncoded;
  const header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.46",
    // 其他头部信息...
  };

  const response = await fetch(baseUrl, { headers: header, redirect: 'manual' })
    .then(response => response.text())
    .then(async html => {
      const $ = cheerio.load(html);
      const results = [];
      const links = $('h3.c-title');

      // 遍历搜索结果
      links.each((i, element) => {
        if (i < result_num) {
          const title = $(element).text();
          const href = $(element).find('a').attr('href');
          if (title && href) {
            results.push({ title, href });
          }
        }
      });

      return results;
    });

  return response;
}

3. 提取链接内容

function crawlLinks(link) {
  const header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.46",
    // 其他头部信息...
  };

  const url = link;
  return fetch(url, { headers: header })
    .then(response => response.text())
    .then(html => {
      const $ = cheerio.load(html);
      const content = $('div').text(); // 假设主要内容都在div标签内
      return content;
    });
}

4. 调用AI模型处理内容

async function aiprompt(content, prompt) {
  const model = openaicompatible
    .ChatTextGenerator({
      api: new BaseUrlApiConfiguration({
        baseUrl: "略",
        headers: {
          Authorization: `empty`,
        },
      }),
      provider: "openaicompatible-togetherai",
      model: "llama3"
    }).withInstructionPrompt();

  const result = await generateText({
    model,
    prompt: {
      system: prompt,
      instruction: content,
    },
  });

  return result;
}

5. 运行代码

const allLinks = await crawlPages("RISC-V模型", 2);
console.log(allLinks);

// 对每个链接进行内容抓取
for (const link of allLinks) {
  const content = await crawlLinks(link.href);
  console.log(content);

  // 使用AI模型处理内容
  const processedContent = await aiprompt(content, "你只能以下文本中提取并保留有关 RISC-V模型 的所有信息并用中文输出。");
  console.log(processedContent);
}

四、总结

通过以上步骤,我们实现了从百度搜索结果中抓取指定关键词的相关网页链接,并进一步提取这些网页的内容。此外,还利用了一个AI模型对抓取的内容进行了处理,以提取出更具体的信息。这种方法可以广泛应用于数据挖掘、市场研究等领域。

需要注意的是,实际应用中可能还需要考虑更多因素,比如反爬虫策略、请求频率限制等。同时,对于AI模型的选择和调用也需要根据具体需求进行调整。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天不熬夜!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值