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): keep urls from the other sitemaps when one sitemap is malformed (#4249)
Jay Hemnani9e6d897a3e13
diff --git a/packages/utils/src/internals/sitemap.ts b/packages/utils/src/internals/sitemap.tsindex 259ec6f66..0959372da 100644--- a/packages/utils/src/internals/sitemap.ts+++ b/packages/utils/src/internals/sitemap.ts@@ -384,48 +384,68 @@ export async function* parseSitemap<T extends ParseSitemapOptions>(// the loop (per-entry warnings could flood the log; individual drops are logged at debug level).let droppedUrlEntries = 0;- for await (const item of items) {- if (item.type === 'sitemapUrl' && !visitedSitemapUrls.has(item.url)) {- if (nestedSitemapFilter && !nestedSitemapFilter(item.url)) {- logger?.debug(`Skipping sitemap ${item.url} due to nestedSitemapFilter.`);- continue;+ const iterator = items[Symbol.asyncIterator]();+ try {+ while (true) {+ let next: IteratorResult<SitemapItem>;+ try {+ next = await iterator.next();+ } catch (e) {+ // Parsing failed: give up on this sitemap, keep the others.+ // Raw sources already logged the error in their pipeline callback.+ if (source.type !== 'raw') {+ logger?.warning(`Malformed sitemap content: ${source.url} (${e})`);+ }+ break;}+ if (next.done) break;+ const item = next.value;- // Keep only nested sitemaps matching the strategy (and using http(s)) relative to the- // parent. Raw string sources have no parent URL, so the check is skipped.- if (source.type === 'url') {- const { allowed, reason } = filterUrl(item.url, sitemapUrl!, enqueueStrategy);- if (!allowed) {- logger?.warning(`Skipping nested sitemap ${item.url} (parent ${source.url}): ${reason}.`);+ if (item.type === 'sitemapUrl' && !visitedSitemapUrls.has(item.url)) {+ if (nestedSitemapFilter && !nestedSitemapFilter(item.url)) {+ logger?.debug(`Skipping sitemap ${item.url} due to nestedSitemapFilter.`);continue;}- }- sources.push({ type: 'url', url: item.url, depth: (source.depth ?? 0) + 1 });- if (emitNestedSitemaps) {- yield { loc: item.url, originSitemapUrl: null } as any;- }- }+ // Keep only nested sitemaps matching the strategy (and using http(s)) relative to the+ // parent. Raw string sources have no parent URL, so the check is skipped.+ if (source.type === 'url') {+ const { allowed, reason } = filterUrl(item.url, sitemapUrl!, enqueueStrategy);+ if (!allowed) {+ logger?.warning(`Skipping nested sitemap ${item.url} (parent ${source.url}): ${reason}.`);+ continue;+ }+ }- if (item.type === 'url') {- // Keep only URL entries that match the enqueue strategy relative to the parent (see above).- if (source.type === 'url') {- const { allowed, reason } = filterUrl(item.loc, sitemapUrl!, enqueueStrategy);- if (!allowed) {- droppedUrlEntries++;- logger?.debug(`Skipping sitemap URL ${item.loc} (parent ${source.url}): ${reason}.`);- continue;+ sources.push({ type: 'url', url: item.url, depth: (source.depth ?? 0) + 1 });+ if (emitNestedSitemaps) {+ yield { loc: item.url, originSitemapUrl: null } as any;}}- yield {- ...item,- originSitemapUrl:- source.type === 'url'- ? source.url- : `raw://${createHash('sha256').update(source.content).digest('base64')}`,- };+ if (item.type === 'url') {+ // Keep only URL entries that match the enqueue strategy relative to the parent (see above).+ if (source.type === 'url') {+ const { allowed, reason } = filterUrl(item.loc, sitemapUrl!, enqueueStrategy);+ if (!allowed) {+ droppedUrlEntries++;+ logger?.debug(`Skipping sitemap URL ${item.loc} (parent ${source.url}): ${reason}.`);+ continue;+ }+ }++ yield {+ ...item,+ originSitemapUrl:+ source.type === 'url'+ ? source.url+ : `raw://${createHash('sha256').update(source.content).digest('base64')}`,+ };+ }}+ } finally {+ // Mirrors `for await` cleanup: destroys the stream when we stop early or the consumer bails out.+ await iterator.return?.();}if (droppedUrlEntries > 0 && source.type === 'url') {diff --git a/test/utils/sitemap.test.ts b/test/utils/sitemap.test.tsindex 41ca668d1..70c82c6b3 100644--- a/test/utils/sitemap.test.ts+++ b/test/utils/sitemap.test.ts@@ -145,6 +145,21 @@ describe('Sitemap', () => {'</sitemapindex>',].join('\n'),)+ .get('/sitemap_parent_with_malformed_child.xml')+ .reply(+ 200,+ [+ '<?xml version="1.0" encoding="UTF-8"?>',+ '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',+ '<sitemap>',+ '<loc>http://not-exists.com/not_actual_xml.xml</loc>',+ '</sitemap>',+ '<sitemap>',+ '<loc>http://not-exists.com/sitemap_child.xml</loc>',+ '</sitemap>',+ '</sitemapindex>',+ ].join('\n'),+ ).get('/not_actual_xml.xml').reply(200,@@ -409,6 +424,22 @@ describe('Sitemap', () => {expect(sitemap.urls).toEqual([]);});+ it('keeps urls from other sitemaps when one of them is malformed', async () => {+ const sitemap = await Sitemap.load(+ ['http://not-exists.com/not_actual_xml.xml', 'http://not-exists.com/sitemap_child.xml'],+ undefined,+ { httpClient: new FetchHttpClient() },+ );+ expect(sitemap.urls).toHaveLength(5);+ });++ it('keeps urls from other nested sitemaps when one of them is malformed', async () => {+ const sitemap = await Sitemap.load('http://not-exists.com/sitemap_parent_with_malformed_child.xml', undefined, {+ httpClient: new FetchHttpClient(),+ });+ expect(sitemap.urls).toHaveLength(5);+ });+it('handles CDATA in loc tags', async () => {const sitemap = await Sitemap.load('http://not-exists.com/sitemap_cdata.xml', undefined, {httpClient: new FetchHttpClient(),