Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
fix(utils): ignore microdata inside <template> elements (#4400)
SwastikTripathi74166737df05
diff --git a/packages/utils/src/internals/extract-microdata.ts b/packages/utils/src/internals/extract-microdata.tsindex 169b228d9..ce5a0ea22 100644--- a/packages/utils/src/internals/extract-microdata.ts+++ b/packages/utils/src/internals/extract-microdata.ts@@ -41,7 +41,7 @@ export async function extractMicrodata(htmlOrCheerioElement: string | CheerioAPIreturn $('[itemscope]').toArray()- .filter((element) => !('itemprop' in element.attribs))+ .filter((element) => !('itemprop' in element.attribs) && !isInsideTemplate(element)).map((element) => parseItem(context, element, new Set()));}@@ -105,7 +105,8 @@ function collectFromNodes(nodes: AnyNode[], elements: Element[], visited: Set<El}// A nested item owns everything below it, so its subtree is not part of the enclosing item.- if (!('itemscope' in node.attribs)) {+ // A `<template>`'s content is an inert fragment, not part of the document.+ if (!('itemscope' in node.attribs) && node.tagName.toLowerCase() !== 'template') {collectFromNodes(node.children, elements, visited);}}@@ -116,7 +117,7 @@ function indexIds($: CheerioAPI): Map<string, Element> {for (const element of $('[id]').toArray()) {// Duplicate ids are invalid HTML; `getElementById` resolves them to the first element.- if (!index.has(element.attribs.id)) {+ if (!index.has(element.attribs.id) && !isInsideTemplate(element)) {index.set(element.attribs.id, element);}}@@ -124,6 +125,21 @@ function indexIds($: CheerioAPI): Map<string, Element> {return index;}+/**+ * Cheerio keeps a `<template>`'s content as its children, but in the DOM that content is a separate+ * inert fragment, so its items and ids are not part of the document (framework placeholders like+ * `<template x-for>` would otherwise show up as items with empty or `{{ mustache }}` values).+ */+function isInsideTemplate(element: Element): boolean {+ for (let parent = element.parent; parent; parent = parent.parent) {+ if (isTag(parent) && parent.tagName.toLowerCase() === 'template') {+ return true;+ }+ }++ return false;+}+function getPropertyValue(context: ExtractionContext, element: Element, ancestors: Set<Element>): MicrodataValue {if ('itemscope' in element.attribs) {// `itemref` can point back at an enclosing item, which the spec treats as an error.diff --git a/test/utils/extract-microdata.test.ts b/test/utils/extract-microdata.test.tsindex da50b712d..2caf1923f 100644--- a/test/utils/extract-microdata.test.ts+++ b/test/utils/extract-microdata.test.ts@@ -168,4 +168,33 @@ describe('extractMicrodata', () => {},]);});++ it('ignores the inert content of <template> elements', async () => {+ // Framework placeholders (Alpine's `x-for`, Vue, Lit) are not part of the document in a browser.+ const items = await extractMicrodata(`+ <div itemscope itemtype="https://schema.org/ItemList" itemref="offer-price">+ <template x-for="product in products">+ <div itemprop="itemListElement" itemscope itemtype="https://schema.org/Product">+ <span itemprop="name" x-text="product.name"></span>+ </div>+ </template>+ <div itemprop="itemListElement" itemscope itemtype="https://schema.org/Product">+ <span itemprop="name">Rendered</span>+ </div>+ </div>+ <template>+ <div itemscope itemtype="https://schema.org/Offer">+ <span id="offer-price" itemprop="price">{{ price }}</span>+ </div>+ </template>`);++ expect(items).toEqual([+ {+ type: ['https://schema.org/ItemList'],+ properties: {+ itemListElement: { type: ['https://schema.org/Product'], properties: { name: 'Rendered' } },+ },+ },+ ]);+ });});