langcode
Version:
A Plugin-Based Framework for Managing and Using LangChain
84 lines (83 loc) • 3.16 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const cheerio_1 = require("cheerio");
const types_1 = require("../../types");
const axios_1 = __importDefault(require("axios"));
class CheerioScraperPlugin {
constructor() {
this.name = "cheerioScraper";
this.description = "Cheerio ile HTML parse edip sayfa içeriğini ayrıştırma plugin'i.";
this.type = types_1.PluginType.Tool;
this.RunConfigExample = {
url: "",
selector: "",
attribute: "",
returnHtml: false
};
this.InitConfigExample = {
userAgent: "Mozilla/5.0 (compatible; CheerioBot/1.0)",
};
this.userAgent = null;
}
expose() {
return {
name: this.name,
description: this.description,
type: this.type,
InitConfigExample: this.InitConfigExample,
RunConfigExample: this.RunConfigExample,
userAgent: this.userAgent,
};
}
async init(config) {
const { userAgent } = config;
this.userAgent = userAgent || "Mozilla/5.0 (compatible; CheerioBot/1.0)";
}
async run(args) {
const { url, selector, attribute, returnHtml } = args;
if (!url) {
throw new Error("Bir 'url' parametresi vermeniz gerekiyor.");
}
// 2) HTTP isteği yap
let responseData;
try {
const response = await axios_1.default.get(url, {
headers: {
"User-Agent": this.userAgent || "CheerioBot",
},
});
responseData = response.data;
}
catch (err) {
throw new Error(`HTTP isteği başarısız: ${err.message}`);
}
// 3) Cheerio ile parse et (Cheerio v2+)
const $ = (0, cheerio_1.load)(responseData);
// Kullanıcı bir 'selector' tanımladıysa, ilgili öğeleri bul
if (selector) {
const elements = $(selector);
if (elements.length === 0) {
return { result: null, message: "Seçiciye uygun öğe bulunamadı." };
}
// attribute varsa, bu attribute değerlerini döndürelim (ör. 'href', 'src')
if (attribute) {
const values = elements.map((i, el) => $(el).attr(attribute)).get();
return { result: values };
}
// returnHtml == true ise, öğelerin HTML çıktısını al
if (returnHtml) {
const htmlValues = elements.map((i, el) => $.html(el)).get();
return { result: htmlValues };
}
// Varsayılan: text() döndürelim
const textValues = elements.map((i, el) => $(el).text()).get();
return { result: textValues };
}
// Seçici yoksa, sayfanın tüm HTML çıktısını döndürelim
return { html: $.html() };
}
}
exports.default = CheerioScraperPlugin;