crw-extract 0.3.5

HTML extraction and markdown conversion engine for the CRW web scraper
Documentation
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use lol_html::{RewriteStrSettings, element, rewrite_str};
use scraper::{Html, Selector};
use std::collections::HashSet;

/// Clean HTML by stripping scripts, styles, and optionally non-content elements.
/// Then apply include_tags/exclude_tags via scraper.
pub fn clean_html(
    html: &str,
    only_main_content: bool,
    include_tags: &[String],
    exclude_tags: &[String],
) -> Result<String, String> {
    // Phase 1: lol_html streaming removal of always-unwanted tags.
    let mut handlers = vec![
        element!("script", |el| {
            el.remove();
            Ok(())
        }),
        element!("style", |el| {
            el.remove();
            Ok(())
        }),
        element!("noscript", |el| {
            el.remove();
            Ok(())
        }),
        element!("iframe", |el| {
            el.remove();
            Ok(())
        }),
        element!("svg", |el| {
            el.remove();
            Ok(())
        }),
        element!("canvas", |el| {
            el.remove();
            Ok(())
        }),
        // Remove images with data: URIs (base64 blobs bloat markdown output).
        element!("img", |el| {
            if let Some(src) = el.get_attribute("src")
                && src.starts_with("data:")
            {
                el.remove();
            }
            Ok(())
        }),
    ];

    if only_main_content {
        handlers.push(element!("nav", |el| {
            el.remove();
            Ok(())
        }));
        handlers.push(element!("footer", |el| {
            el.remove();
            Ok(())
        }));
        handlers.push(element!("header", |el| {
            el.remove();
            Ok(())
        }));
        handlers.push(element!("aside", |el| {
            el.remove();
            Ok(())
        }));
        handlers.push(element!("menu", |el| {
            el.remove();
            Ok(())
        }));
        // Dropdown <select> elements are never publishable content.
        handlers.push(element!("select", |el| {
            el.remove();
            Ok(())
        }));

        // Remove elements whose class or id matches common non-content patterns.
        // Covers sidebars, TOC, navigation, ads, related/recommended sections,
        // cookie banners, share widgets, and comment sections.
        //
        // IMPORTANT: Never remove structural elements (html, head, body) — that
        // would nuke the entire page. Also skip <main> since it typically
        // wraps the primary content we want to keep.
        handlers.push(element!("*", |el| {
            let tag = el.tag_name();
            let tag_name = tag.as_str();
            if matches!(tag_name, "html" | "head" | "body" | "main") {
                return Ok(());
            }

            let class = el.get_attribute("class").unwrap_or_default().to_lowercase();
            let id = el.get_attribute("id").unwrap_or_default().to_lowercase();

            // Check each CSS class token and the id individually.
            // Per-token substring matching avoids cross-token false positives
            // (e.g. "vector-toc-available skin-theme" wouldn't match "toc" on
            // a combined string that also contains the other classes).
            let combined = format!("{class} {id}");

            const NOISE_PATTERNS: &[&str] = &[
                "sidebar",
                "table-of-contents",
                "tableofcontents",
                "infobox",
                "navbox",
                "nav-box",
                "navigation",
                "breadcrumb",
                "cookie",
                "consent",
                "banner",
                "disqus",
                "advert",
                "popup",
                "modal",
                "newsletter",
                "subscribe",
                "printfooter",
                "catlinks",
                "mw-panel",
                "mw-navigation",
                "sitesub",
                "jump-to-nav",
                "mw-editsection",
                "reflist",
                "mw-references",
                "authority-control",
                "mw-indicators",
                "sistersitebox",
                "mbox",
                "ambox",
                "ombox",
                "hatnote",
                "shortdescription",
                "sphinxsidebar",
                "sphinxfooter",
                "copyright",
                "dropdown",
                "city-selector",
                "location-selector",
            ];

            // Patterns that need exact token matching (too short/generic for substring).
            // Checked against individual class names and the id value.
            const NOISE_EXACT_TOKENS: &[&str] = &[
                "toc",     // table of contents — "toc" but not "vector-toc-available"
                "share",   // share widgets — not "share-price" or "shareholder"
                "social",  // social buttons
                "related", // related content
                "recommended",
                "comment", // comment sections — not "uncommented"
                "footer",  // div.footer (e.g. Sphinx "Created using Sphinx")
            ];

            // Prefix patterns: match tokens that START with these strings.
            const NOISE_PREFIXES: &[&str] = &[
                "ad-", // ad containers — not "load-more", "typeahead"
                "ads-",
            ];

            let is_noise = NOISE_PATTERNS.iter().any(|p| combined.contains(p)) || {
                let tokens_iter = class.split_whitespace().chain(std::iter::once(id.as_str()));
                tokens_iter.into_iter().any(|tok| {
                    NOISE_EXACT_TOKENS.contains(&tok)
                        || NOISE_PREFIXES.iter().any(|pre| tok.starts_with(pre))
                })
            };

            if is_noise {
                el.remove();
                return Ok(());
            }

            // Remove elements with ARIA landmark roles that indicate non-content areas.
            let role = el.get_attribute("role").unwrap_or_default().to_lowercase();
            if matches!(
                role.as_str(),
                "contentinfo" | "navigation" | "banner" | "complementary"
            ) {
                el.remove();
                return Ok(());
            }

            Ok(())
        }));
    }

    let mut result = rewrite_str(
        html,
        RewriteStrSettings {
            element_content_handlers: handlers,
            ..Default::default()
        },
    )
    .map_err(|e| e.to_string())?;

    // Phase 2: If include_tags specified, only keep content matching those selectors.
    if !include_tags.is_empty() {
        result = keep_only_selectors(&result, include_tags);
    }

    // Phase 3: Apply exclude_tags — parse again and collect text/html without excluded.
    if !exclude_tags.is_empty() {
        result = remove_by_selectors(&result, exclude_tags);
    }

    Ok(result)
}

/// Keep only the HTML of elements matching any of the given CSS selectors.
fn keep_only_selectors(html: &str, selectors: &[String]) -> String {
    let doc = Html::parse_document(html);
    let mut parts = Vec::new();

    for sel_str in selectors {
        match Selector::parse(sel_str) {
            Ok(sel) => {
                for el in doc.select(&sel) {
                    parts.push(el.html());
                }
            }
            Err(e) => {
                tracing::warn!("Invalid CSS selector '{}': {:?}", sel_str, e);
            }
        }
    }

    if parts.is_empty() {
        return html.to_string();
    }

    parts.join("\n")
}

/// Remove elements matching CSS selectors from the document.
/// Re-serializes the tree, skipping matched subtrees via tree node indices.
fn remove_by_selectors(html: &str, selectors: &[String]) -> String {
    let doc = Html::parse_document(html);

    // Collect pointers to matched elements for exclusion.
    // SAFETY: All pointers point into `doc` which lives for the entire function scope.
    // We only compare pointers (never dereference), so this is safe as long as `doc` is alive.
    let mut skip_ptrs: HashSet<*const scraper::node::Element> = HashSet::new();
    for sel_str in selectors {
        match Selector::parse(sel_str) {
            Ok(sel) => {
                for el in doc.select(&sel) {
                    skip_ptrs.insert(el.value() as *const _);
                }
            }
            Err(e) => {
                tracing::warn!("Invalid CSS selector '{}': {:?}", sel_str, e);
            }
        }
    }

    if skip_ptrs.is_empty() {
        return html.to_string();
    }

    // Re-serialize the root element, skipping excluded subtrees.
    // Pre-allocate output based on input size.
    let root = doc.root_element();
    let mut out = String::with_capacity(html.len());
    collect_excluding(&root, &skip_ptrs, &mut out);
    out
}

fn is_excluded(
    el: &scraper::ElementRef,
    skip_ptrs: &HashSet<*const scraper::node::Element>,
) -> bool {
    let ptr = el.value() as *const scraper::node::Element;
    skip_ptrs.contains(&ptr)
}

fn collect_excluding(
    element: &scraper::ElementRef,
    skip_ptrs: &HashSet<*const scraper::node::Element>,
    out: &mut String,
) {
    if is_excluded(element, skip_ptrs) {
        return;
    }

    let el = element.value();
    out.push('<');
    out.push_str(&el.name.local);
    for (name, value) in el.attrs() {
        out.push(' ');
        out.push_str(name);
        out.push_str("=\"");
        out.push_str(&value.replace('"', "&quot;"));
        out.push('"');
    }
    out.push('>');

    for child in element.children() {
        match child.value() {
            scraper::node::Node::Text(text) => {
                out.push_str(text);
            }
            scraper::node::Node::Element(_) => {
                if let Some(child_el) = scraper::ElementRef::wrap(child) {
                    collect_excluding(&child_el, skip_ptrs, out);
                }
            }
            _ => {}
        }
    }

    let self_closing = matches!(
        &*el.name.local,
        "br" | "hr"
            | "img"
            | "input"
            | "meta"
            | "link"
            | "area"
            | "base"
            | "col"
            | "embed"
            | "source"
            | "track"
            | "wbr"
    );
    if !self_closing {
        out.push_str("</");
        out.push_str(&el.name.local);
        out.push('>');
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn strips_scripts_and_styles() {
        let html =
            r#"<html><body><script>alert(1)</script><p>Hello</p><style>x{}</style></body></html>"#;
        let result = clean_html(html, false, &[], &[]).unwrap();
        assert!(!result.contains("<script>"));
        assert!(!result.contains("<style>"));
        assert!(result.contains("Hello"));
    }

    #[test]
    fn strips_nav_footer_in_main_content_mode() {
        let html = r#"<body><nav>Menu</nav><article>Content</article><footer>Foot</footer></body>"#;
        let result = clean_html(html, true, &[], &[]).unwrap();
        assert!(!result.contains("Menu"));
        assert!(!result.contains("Foot"));
        assert!(result.contains("Content"));
    }

    #[test]
    fn exclude_tags_removes_matching_elements() {
        let html = r#"<body><div class="ad">Ad stuff</div><p>Real content</p></body>"#;
        let result = clean_html(html, false, &[], &["div.ad".into()]).unwrap();
        assert!(!result.contains("Ad stuff"));
        assert!(result.contains("Real content"));
    }

    #[test]
    fn does_not_remove_html_body_with_noise_classes() {
        // Wikipedia's <html> has classes like "vector-toc-available" containing "toc".
        // The noise handler must skip structural elements to avoid nuking the page.
        let html = r#"<html class="vector-toc-available"><body><main class="mw-body"><p>Content</p></main></body></html>"#;
        let result = clean_html(html, true, &[], &[]).unwrap();
        assert!(
            result.contains("Content"),
            "Structural elements must not be removed by noise patterns"
        );
    }

    #[test]
    fn strips_role_contentinfo_in_main_content_mode() {
        let html = r#"<body><div role="contentinfo">Copyright 2024</div><p>Content</p><div role="navigation">Nav</div></body>"#;
        let result = clean_html(html, true, &[], &[]).unwrap();
        assert!(!result.contains("Copyright"));
        assert!(!result.contains("Nav"));
        assert!(result.contains("Content"));
    }

    #[test]
    fn strips_sphinx_patterns_in_main_content_mode() {
        let html = r#"<body><div class="sphinxsidebar">Sidebar</div><p>Content</p><div class="copyright">Copyright</div></body>"#;
        let result = clean_html(html, true, &[], &[]).unwrap();
        assert!(!result.contains("Sidebar"));
        assert!(!result.contains("Copyright"));
        assert!(result.contains("Content"));
    }

    #[test]
    fn include_tags_keeps_only_matching() {
        let html =
            r#"<body><nav>Nav</nav><article><p>Article</p></article><footer>Foot</footer></body>"#;
        let result = clean_html(html, false, &["article".into()], &[]).unwrap();
        assert!(result.contains("Article"));
        assert!(!result.contains("Nav"));
        assert!(!result.contains("Foot"));
    }
}