import fetch from 'node-fetch';
import * as cheerio from 'cheerio';
class WebLoader {
constructor() {
this.chunkSize = 1000;
this.chunkOverlap = 200;
}
async loadWebPage(url) {
try {
const response = await fetch(url);
const html = await response.text();
const $ = cheerio.load(html);
$('script, style, nav, footer, aside').remove();
let text = $('body').text();
text = text.replace(/\s+/g, ' ').trim();
return text;
} catch (error) {
console.error(`加载网页失败: ${url}`, error);
throw error;
}
}
splitText(text) {
const chunks = [];
let start = 0;
while (start < text.length) {
let end = start + this.chunkSize;
if (end > text.length) {
end = text.length;
}
chunks.push(text.slice(start, end));
start += this.chunkSize - this.chunkOverlap;
}
return chunks;
}
async processWebPage(url) {
const text = await this.loadWebPage(url);
const chunks = this.splitText(text);
const documents = chunks.map((chunk, index) => {
const id = `${new URL(url).hostname}_chunk_${index}`;
return {
id,
text: chunk,
metadata: {
source: url,
chunkIndex: index,
totalChunks: chunks.length
}
};
});
return documents;
}
async processWebPages(urls) {
let allDocuments = [];
for (const url of urls) {
const documents = await this.processWebPage(url);
allDocuments = allDocuments.concat(documents);
}
return allDocuments;
}
}
export default WebLoader;