|
1 | 1 | import type { CheerioAPI } from 'crawlee'; |
2 | 2 | import { log } from 'crawlee'; |
| 3 | +import type { Element } from 'domhandler'; |
3 | 4 |
|
4 | | -import type { ContentScraperSettings, OpenGraphProperty } from '../types.js'; |
| 5 | +import type { ContentScraperSettings, Link, OpenGraphProperty } from '../types.js'; |
5 | 6 | import { readableText } from './text-extractor.js'; |
6 | 7 |
|
7 | 8 | const SKIP_CHILD_OF_ELEMENT_SELECTORS = ['.crawlee-iframe-replacement *', 'svg *'].join(', '); |
@@ -55,6 +56,86 @@ export function extractCanonicalUrl($: CheerioAPI, baseUrl: string): string | un |
55 | 56 | return undefined; |
56 | 57 | } |
57 | 58 |
|
| 59 | +/** |
| 60 | + * A bare same-page anchor (`#section`, `#`) points into the page we already have. Hash-routing links of |
| 61 | + * single-page apps (`#/quickstart`, `#!/page`) are navigation, so they are not anchors. |
| 62 | + */ |
| 63 | +const isSamePageAnchor = (href: string) => href.startsWith('#') && !/^#[!/]/.test(href); |
| 64 | + |
| 65 | +/** The text of a link is cut to this many characters, so that a link wrapping a whole card stays short. */ |
| 66 | +const MAX_LINK_TEXT_LENGTH = 200; |
| 67 | + |
| 68 | +/** Elements whose content is code or markup that is not shown, even when they sit inside a link. */ |
| 69 | +const NON_VISIBLE_TEXT_SELECTOR = 'script, style, noscript, template'; |
| 70 | + |
| 71 | +/** Collapses whitespace and cuts to `MAX_LINK_TEXT_LENGTH` characters (code points, so that no emoji is split). */ |
| 72 | +function normalizeLinkText(text: string | undefined): string { |
| 73 | + const collapsed = (text ?? '').replace(/\s+/g, ' ').trim(); |
| 74 | + return Array.from(collapsed).slice(0, MAX_LINK_TEXT_LENGTH).join('').trim(); |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * The visible text of a link, falling back to its accessible names for icon and image links: the |
| 79 | + * `aria-label`, `title` and `alt` attributes, and the `alt` of an image inside it. The result is plain text. |
| 80 | + */ |
| 81 | +function extractLinkText($: CheerioAPI, element: Element): string { |
| 82 | + const $el = $(element); |
| 83 | + const getVisibleText = () => { |
| 84 | + const $copy = $el.clone(); |
| 85 | + $copy.find(NON_VISIBLE_TEXT_SELECTOR).remove(); |
| 86 | + return $copy.text(); |
| 87 | + }; |
| 88 | + const candidates = [ |
| 89 | + getVisibleText, |
| 90 | + () => $el.attr('aria-label'), |
| 91 | + () => $el.attr('title'), |
| 92 | + () => $el.attr('alt'), |
| 93 | + () => $el.find('img[alt]').first().attr('alt'), |
| 94 | + ]; |
| 95 | + |
| 96 | + for (const candidate of candidates) { |
| 97 | + const text = normalizeLinkText(candidate()); |
| 98 | + if (text) return text; |
| 99 | + } |
| 100 | + return ''; |
| 101 | +} |
| 102 | + |
| 103 | +/** |
| 104 | + * Collects every `<a href>` and image map `<area href>` on the page as a de-duplicated list of links, with |
| 105 | + * absolute HTTP(S) URLs resolved against `baseUrl` and the visible text of the link when it has any. |
| 106 | + * Non-HTTP(S) schemes (`mailto:`, `tel:`, `javascript:`, …), unparseable hrefs, bare same-page anchors |
| 107 | + * (`#section`) and unrendered template hrefs (`{{ item.url }}`) are dropped. Hash-routing links (`#/page`, |
| 108 | + * `#!/page`) are kept. Order of first appearance is preserved, and a URL that appears more than once keeps |
| 109 | + * the first non-empty text. |
| 110 | + */ |
| 111 | +export function extractLinks($: CheerioAPI, baseUrl: string): Link[] { |
| 112 | + const links = new Map<string, Link>(); |
| 113 | + |
| 114 | + for (const element of $('a[href], area[href]').get()) { |
| 115 | + const href = $(element).attr('href')?.trim(); |
| 116 | + if (!href || isSamePageAnchor(href) || href.includes('{{')) continue; |
| 117 | + |
| 118 | + let url: URL; |
| 119 | + try { |
| 120 | + url = new URL(href, baseUrl); |
| 121 | + } catch { |
| 122 | + // Ignore hrefs that don't resolve to a valid URL. |
| 123 | + continue; |
| 124 | + } |
| 125 | + if (url.protocol !== 'http:' && url.protocol !== 'https:') continue; |
| 126 | + |
| 127 | + const text = extractLinkText($, element); |
| 128 | + const existing = links.get(url.href); |
| 129 | + if (!existing) { |
| 130 | + links.set(url.href, text ? { url: url.href, text } : { url: url.href }); |
| 131 | + } else if (!existing.text && text) { |
| 132 | + existing.text = text; |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + return [...links.values()]; |
| 137 | +} |
| 138 | + |
58 | 139 | export function extractOpenGraphProperties($: CheerioAPI): OpenGraphProperty[] | undefined { |
59 | 140 | const properties = $(OPEN_GRAPH_SELECTOR).get().flatMap((element) => { |
60 | 141 | const property = $(element).attr('property'); |
|
0 commit comments