目录
使用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模型的选择和调用也需要根据具体需求进行调整。