Spaces:
Sleeping
Sleeping
File size: 5,259 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | // TODO: refactor
import { AnyNode, Cheerio, load } from "cheerio"; // rustified
import { ScrapeOptions } from "../../../controllers/v2/types";
import { transformHtml } from "@mendable/firecrawl-rs";
import { logger } from "../../../lib/logger";
import { queryOMCESignatures } from "../../../services/index";
const excludeNonMainTags = [
"header",
"footer",
"nav",
"aside",
".header",
".top",
".navbar",
"#header",
".footer",
".bottom",
"#footer",
".sidebar",
".side",
".aside",
"#sidebar",
".modal",
".popup",
"#modal",
".overlay",
".ad",
".ads",
".advert",
"#ad",
".lang-selector",
".language",
"#language-selector",
".social",
".social-media",
".social-links",
"#social",
".menu",
".navigation",
"#nav",
".breadcrumbs",
"#breadcrumbs",
".share",
"#share",
".widget",
"#widget",
".cookie",
"#cookie",
];
const forceIncludeMainTags = [
"#main",
".swoogo-cols",
".swoogo-text",
".swoogo-table-div",
".swoogo-space",
".swoogo-alert",
".swoogo-sponsors",
".swoogo-title",
".swoogo-tabs",
".swoogo-logo",
".swoogo-image",
".swoogo-button",
".swoogo-agenda",
];
export const htmlTransform = async (
html: string,
url: string,
scrapeOptions: ScrapeOptions,
) => {
let omceSignatures: string[] | undefined = undefined;
if (scrapeOptions.__experimental_omce) {
try {
const hostname =
scrapeOptions.__experimental_omceDomain || new URL(url).hostname;
omceSignatures = await queryOMCESignatures(hostname);
logger.info("Got OMCE signatures", { signatures: omceSignatures.length });
} catch (error) {
logger.warn("Failed to get omce signatures.", {
error,
scrapeURL: url,
module: "scrapeURL",
method: "htmlTransform",
});
}
}
try {
return await transformHtml({
html,
url,
includeTags: (scrapeOptions.includeTags ?? [])
.map(x => x.trim())
.filter(x => x.length !== 0),
excludeTags: (scrapeOptions.excludeTags ?? [])
.map(x => x.trim())
.filter(x => x.length !== 0),
onlyMainContent: scrapeOptions.onlyMainContent,
omceSignatures,
});
} catch (error) {
logger.warn("Failed to call html-transformer! Falling back to cheerio...", {
error,
module: "scrapeURL",
method: "htmlTransform",
});
}
let soup = load(html);
// remove unwanted elements
if (
scrapeOptions.includeTags &&
scrapeOptions.includeTags.filter(x => x.trim().length !== 0).length > 0
) {
// Create a new root element to hold the tags to keep
const newRoot = load("<div></div>")("div");
scrapeOptions.includeTags.forEach(tag => {
soup(tag).each((_, element) => {
newRoot.append(soup(element).clone());
});
});
soup = load(newRoot.html() ?? "");
}
soup("script, style, noscript, meta, head").remove();
if (
scrapeOptions.excludeTags &&
scrapeOptions.excludeTags.filter(x => x.trim().length !== 0).length > 0
) {
scrapeOptions.excludeTags.forEach(tag => {
let elementsToRemove: Cheerio<AnyNode>;
if (tag.startsWith("*") && tag.endsWith("*")) {
let classMatch = false;
const regexPattern = new RegExp(tag.slice(1, -1), "i");
elementsToRemove = soup("*").filter((i, element) => {
if (element.type === "tag") {
const attributes = element.attribs;
const tagNameMatches = regexPattern.test(element.name);
const attributesMatch = Object.keys(attributes).some(attr =>
regexPattern.test(`${attr}="${attributes[attr]}"`),
);
if (tag.startsWith("*.")) {
classMatch = Object.keys(attributes).some(attr =>
regexPattern.test(`class="${attributes[attr]}"`),
);
}
return tagNameMatches || attributesMatch || classMatch;
}
return false;
});
} else {
elementsToRemove = soup(tag);
}
elementsToRemove.remove();
});
}
if (scrapeOptions.onlyMainContent) {
excludeNonMainTags.forEach(tag => {
const elementsToRemove = soup(tag).filter(
forceIncludeMainTags.map(x => ":not(:has(" + x + "))").join(""),
);
elementsToRemove.remove();
});
}
// always return biggest image
soup("img[srcset]").each((_, el) => {
const sizes = el.attribs.srcset.split(",").map(x => {
const tok = x.trim().split(" ");
return {
url: tok[0],
size: parseInt((tok[1] ?? "1x").slice(0, -1), 10),
isX: (tok[1] ?? "").endsWith("x"),
};
});
if (sizes.every(x => x.isX) && el.attribs.src) {
sizes.push({
url: el.attribs.src,
size: 1,
isX: true,
});
}
sizes.sort((a, b) => b.size - a.size);
el.attribs.src = sizes[0]?.url;
});
// absolute links
soup("img[src]").each((_, el) => {
try {
el.attribs.src = new URL(el.attribs.src, url).href;
} catch (_) {}
});
soup("a[href]").each((_, el) => {
try {
el.attribs.href = new URL(el.attribs.href, url).href;
} catch (_) {}
});
const cleanedHtml = soup.html();
return cleanedHtml;
};
|