Spaces:
Sleeping
Sleeping
File size: 2,710 Bytes
097eaf0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | import { load } from "cheerio";
import { logger } from "../../../lib/logger";
import { extractAttributes as _extractAttributes } from "@mendable/firecrawl-rs";
type AttributeResult = {
selector: string;
attribute: string;
values: string[];
};
type AttributeSelector = {
selector: string;
attribute: string;
};
/**
* Extracts attributes from HTML using Rust html-transformer (with Cheerio fallback)
* @param html - The HTML content to extract from
* @param selectors - Array of selector/attribute pairs to extract
* @returns Array of extracted attribute results
*/
export async function extractAttributes(
html: string,
selectors: AttributeSelector[],
): Promise<AttributeResult[]> {
if (!selectors || selectors.length === 0) {
return [];
}
// Try Rust implementation first (faster, non-blocking)
try {
const results = await _extractAttributes(html, { selectors });
logger.debug("Attribute extraction via Rust", {
selectorsCount: selectors.length,
resultsCount: results.length,
sampleResults: results.slice(0, 2).map(r => ({
selector: r.selector,
attribute: r.attribute,
valuesCount: r.values.length,
})),
});
return results;
} catch (error) {
logger.warn(
"Failed to extract attributes with Rust, falling back to Cheerio",
{
error,
module: "scrapeURL",
method: "extractAttributes",
},
);
}
// Fallback to Cheerio implementation
const results: AttributeResult[] = [];
try {
const $ = load(html);
for (const extraction of selectors) {
const { selector, attribute } = extraction;
const values: string[] = [];
// Find all elements matching the selector
$(selector).each((_, element) => {
// Get the attribute value
// Support both data-* format and without data- prefix
let attrValue = $(element).attr(attribute);
// If not found and attribute doesn't start with 'data-', try with 'data-' prefix
if (!attrValue && !attribute.startsWith("data-")) {
attrValue = $(element).attr(`data-${attribute}`);
}
if (attrValue) {
values.push(attrValue);
}
});
results.push({
selector,
attribute,
values,
});
logger.debug("Attribute extraction via Cheerio fallback", {
selector,
attribute,
valuesCount: values.length,
sample: values.slice(0, 3),
});
}
} catch (error) {
logger.error("Failed to extract attributes with Cheerio fallback", {
error,
module: "scrapeURL",
method: "extractAttributes",
});
}
return results;
}
|