Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/request-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ContentCrawlerStatus, ContentCrawlerTypes } from './const.js';
import { addResultToResponse, responseData, sendResponseIfFinished } from './responses.js';
import type { ContentCrawlerUserData, Output } from './types.js';
import { addTimeMeasureEvent, isActorStandby, transformTimeMeasuresToRelative } from './utils.js';
import { processHtml } from './website-content-crawler/html-processing.js';
import { extractTitle, processHtml } from './website-content-crawler/html-processing.js';
import { htmlToMarkdown } from './website-content-crawler/markdown.js';

let ACTOR_TIMEOUT_AT: number | undefined;
Expand Down Expand Up @@ -136,7 +136,7 @@ async function handleContent(
searchResult: request.userData.searchResult!,
metadata: {
author: $('meta[name=author]').first().attr('content') ?? undefined,
title: $('title').first().text(),
title: extractTitle($),
description: $('meta[name=description]').first().attr('content') ?? undefined,
languageCode: $html.first().attr('lang') ?? undefined,
url: request.url,
Expand Down
25 changes: 24 additions & 1 deletion src/website-content-crawler/html-processing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,28 @@ import { log } from 'crawlee';
import type { ContentScraperSettings } from '../types.js';
import { readableText } from './text-extractor.js';

const SKIP_CHILD_OF_ELEMENT_SELECTORS = ['.crawlee-iframe-replacement *', 'svg *'].join(', ');
const TITLE_SELECTORS = [
`head > title:not(${SKIP_CHILD_OF_ELEMENT_SELECTORS})`,
`title:not(${SKIP_CHILD_OF_ELEMENT_SELECTORS})`,
];

/**
* Extracts the page title (source: Website Content Crawler).
*
* Prefers the `<title>` in `<head>` and ignores `<title>` elements nested in SVGs
* (used there as tooltips) or in Crawlee iframe replacement nodes.
*/
export function extractTitle($: CheerioAPI): string {
for (const selector of TITLE_SELECTORS) {
const title = $(selector).first().text().trim();
if (title) {
return title;
}
}
return '';
}

/**
* Process HTML with the selected HTML transformer (source: Website Content Crawler).
*/
Expand All @@ -18,12 +40,13 @@ export async function processHtml(
$body.find(settings.removeElementsCssSelector).remove();
}
const simplifiedBody = $body.html()?.trim();
const title = extractTitle($);

const simplified = typeof simplifiedBody === 'string'
? `<html lang="">
<head>
<title>
${$('title').text()}
${title}
</title>
</head>
<body>
Expand Down
3 changes: 3 additions & 0 deletions tests/cheerio-crawler.content.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ describe('Cheerio Crawler Content Tests', () => {
expect(pushDataSpy).toHaveBeenCalledTimes(1);
expect(pushDataSpy).toHaveBeenCalledWith(expect.objectContaining({
text: expect.stringContaining('hello world'),
metadata: expect.objectContaining({
title: 'Test Page',
}),
}));
successUrls.add(context.request.url);
},
Expand Down
47 changes: 47 additions & 0 deletions tests/html-processing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { load } from 'cheerio';
import type { CheerioAPI } from 'crawlee';
import { describe, expect, it } from 'vitest';

import { extractTitle } from '../src/website-content-crawler/html-processing.js';

// The `cheerio` version bundled with Crawlee differs from the top-level one, so the types don't match.
const parse = (html: string) => load(html) as unknown as CheerioAPI;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an annoying cast, I think we can solve it by playing with Cheerio versions, I think it was discussed some time ago


describe('extractTitle', () => {
it('should extract the title from somewhere else if not in head', () => {
const $ = parse(`<html>
<head></head>
<body>
<div class="content">The part with the content.</div>
<title>Title in body</title>
</body>
</html>`);
expect(extractTitle($)).toBe('Title in body');
});

it('should ignore titles in SVGs anywhere in the html', () => {
const $ = parse(`<html>
<head><svg><title>Title in head svg</title></svg></head>
<body>
<div class="content">The part with the content.</div>
<svg><title>Title in body svg</title></svg>
</body>
</html>`);
expect(extractTitle($)).toBe('');
});

it('should ignore titles in .crawlee-iframe-replacement anywhere in the html', () => {
const $ = parse(`<html>
<head><div class="crawlee-iframe-replacement"><title>Title in head</title></div></head>
<body>
<div class="crawlee-iframe-replacement"><title>Title in .crawlee-iframe-replacement</title></div>
</body>
</html>`);
expect(extractTitle($)).toBe('');
});

it('should trim surrounding whitespace', () => {
const $ = parse('<html><head><title>\n Test Title \n</title></head><body></body></html>');
expect(extractTitle($)).toBe('Test Title');
});
});
Loading