trafilatura 0.3.0

Extract readable content, comments, and metadata from web pages
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
// Port of go-trafilatura/internal/selector/meta-author.go,
// meta-author-discard.go, meta-title.go, meta-categories.go, meta-tags.go

use crate::dom::{Document, NodeId};
use crate::selector::utils::{contains, get_node_ancestors, lower, starts_with};

/// Rules to find author metadata elements.
///
/// Port of `MetaAuthor`.
pub(crate) const META_AUTHOR: &[super::Rule] =
    &[meta_author_rule1, meta_author_rule2, meta_author_rule3];

/// Rules to discard false-positive author matches.
///
/// Port of `MetaAuthorDiscard`.
pub(crate) const META_AUTHOR_DISCARD: &[super::Rule] =
    &[meta_author_discard_rule1, meta_author_discard_rule2];

/// Rules to find title metadata elements.
///
/// Port of `MetaTitle`.
pub(crate) const META_TITLE: &[super::Rule] =
    &[meta_title_rule1, meta_title_rule2, meta_title_rule3];

/// Rules to find category metadata links.
///
/// Port of `MetaCategories`.
pub(crate) const META_CATEGORIES: &[super::Rule] = &[
    meta_categories_rule1,
    meta_categories_rule2,
    meta_categories_rule3,
    meta_categories_rule4,
    meta_categories_rule5,
    meta_categories_rule6,
];

/// Rules to find tag metadata links.
///
/// Port of `MetaTags`.
pub(crate) const META_TAGS: &[super::Rule] = &[
    meta_tags_rule1,
    meta_tags_rule2,
    meta_tags_rule3,
    meta_tags_rule4,
];

// ---------------------------------------------------------------------------
// MetaAuthor rules
// ---------------------------------------------------------------------------

/// Matches specific author elements by rel, id, class, itemprop, or data-testid.
///
/// Port of `metaAuthorRule1`.
fn meta_author_rule1(doc: &Document, id: NodeId) -> bool {
    let tag = doc.tag_name(id);
    match tag {
        "a" | "address" | "div" | "link" | "p" | "span" | "strong" => {}
        "author" => return true,
        _ => return false,
    }

    let class = doc.class_name(id);
    let elem_id = doc.id_attr(id);
    let rel = doc.get_attribute(id, "rel").unwrap_or_default();
    let item_prop = doc.get_attribute(id, "itemprop").unwrap_or_default();
    let data_test_id = doc.get_attribute(id, "data-testid").unwrap_or_default();

    rel == "author"
        || elem_id == "author"
        || class == "author"
        || item_prop == "author name"
        || rel == "me"
        || contains(&class, "author-name")
        || contains(&class, "AuthorName")
        || contains(&class, "authorName")
        || contains(&class, "author name")
        || data_test_id == "AuthorCard"
        || data_test_id == "AuthorURL"
}

/// Matches generic author containers by class/id/itemprop patterns.
///
/// Port of `metaAuthorRule2`.
fn meta_author_rule2(doc: &Document, id: NodeId) -> bool {
    let tag = doc.tag_name(id);
    match tag {
        "a" | "div" | "h3" | "h4" | "p" | "span" => {}
        _ => return false,
    }

    let class = doc.class_name(id);
    let elem_id = doc.id_attr(id);
    let item_prop = doc.get_attribute(id, "itemprop").unwrap_or_default();

    contains(&class, "author")
        || contains(&elem_id, "author")
        || contains(&item_prop, "author")
        || class == "byline"
        || contains(&class, "channel-name")
        || contains(&elem_id, "zuozhe")
        || contains(&class, "zuozhe")
        || contains(&elem_id, "bianji")
        || contains(&class, "bianji")
        || contains(&elem_id, "xiaobian")
        || contains(&class, "xiaobian")
        || contains(&class, "submitted-by")
        || contains(&class, "posted-by")
        || class == "username"
        || class == "byl"
        || class == "BBL"
        || contains(&class, "journalist-name")
}

/// Matches any element with author-related attributes (last-resort).
///
/// Port of `metaAuthorRule3`.
fn meta_author_rule3(doc: &Document, id: NodeId) -> bool {
    let class = doc.class_name(id);
    let elem_id = doc.id_attr(id);
    let data_component = doc.get_attribute(id, "data-component").unwrap_or_default();
    let item_prop = doc.get_attribute(id, "itemprop").unwrap_or_default();

    contains(&lower(&elem_id), "author")
        || contains(&lower(&class), "author")
        || contains(&class, "screenname")
        || contains(&lower(&data_component), "byline")
        || contains(&item_prop, "author")
        || contains(&class, "writer")
        || contains(&lower(&class), "byline")
}

// ---------------------------------------------------------------------------
// MetaAuthorDiscard rules
// ---------------------------------------------------------------------------

/// Discards comment sections, sidebars, dates, and figures that may contain author-like text.
///
/// Port of `metaAuthorDiscardRule1`.
fn meta_author_discard_rule1(doc: &Document, id: NodeId) -> bool {
    let tag = doc.tag_name(id);
    match tag {
        "a" | "div" | "section" | "span" => {}
        _ => return false,
    }

    let class = doc.class_name(id);
    let elem_id = doc.id_attr(id);
    let data_component = doc.get_attribute(id, "data-component").unwrap_or_default();

    elem_id == "comments"
        || class == "comments"
        || class == "title"
        || class == "date"
        || contains(&elem_id, "commentlist")
        || contains(&class, "commentlist")
        || contains(&class, "sidebar")
        || contains(&class, "is-hidden")
        || contains(&class, "quote")
        || contains(&elem_id, "comment-list")
        || contains(&class, "comment-list")
        || contains(&class, "embedly-instagram")
        || contains(&elem_id, "ProductReviews")
        || starts_with(&elem_id, "comments")
        || contains(&data_component, "Figure")
        || contains(&class, "article-share")
        || contains(&class, "article-support")
        || contains(&class, "print")
        || contains(&class, "category")
        || contains(&class, "meta-date")
        || contains(&class, "meta-reviewer")
        || starts_with(&class, "comments")
        || starts_with(&class, "Comments")
}

/// Discards `<time>` and `<figure>` elements.
///
/// Port of `metaAuthorDiscardRule2`.
fn meta_author_discard_rule2(doc: &Document, id: NodeId) -> bool {
    let tag = doc.tag_name(id);
    tag == "time" || tag == "figure"
}

// ---------------------------------------------------------------------------
// MetaTitle rules
// ---------------------------------------------------------------------------

/// Matches h1/h2 with headline-related class/itemprop.
///
/// Port of `metaTitleRule1`.
fn meta_title_rule1(doc: &Document, id: NodeId) -> bool {
    let tag = doc.tag_name(id);
    match tag {
        "h1" | "h2" => {}
        _ => return false,
    }

    let class = doc.class_name(id);
    let elem_id = doc.id_attr(id);
    let item_prop = doc.get_attribute(id, "itemprop").unwrap_or_default();

    contains(&class, "post-title")
        || contains(&class, "entry-title")
        || contains(&class, "headline")
        || contains(&elem_id, "headline")
        || contains(&item_prop, "headline")
        || contains(&class, "post__title")
        || contains(&class, "article-title")
}

/// Matches any element with class "entry-title" or "post-title".
///
/// Port of `metaTitleRule2`.
fn meta_title_rule2(doc: &Document, id: NodeId) -> bool {
    let class = doc.class_name(id);
    class == "entry-title" || class == "post-title"
}

/// Matches h1/h2/h3 with "title" in class or id.
///
/// Port of `metaTitleRule3`.
fn meta_title_rule3(doc: &Document, id: NodeId) -> bool {
    let tag = doc.tag_name(id);
    match tag {
        "h1" | "h2" | "h3" => {}
        _ => return false,
    }

    let class = doc.class_name(id);
    let elem_id = doc.id_attr(id);

    contains(&class, "title") || contains(&elem_id, "title")
}

// ---------------------------------------------------------------------------
// MetaCategories rules
// ---------------------------------------------------------------------------

/// Matches `<a href>` inside div ancestors with post-meta/entry-meta class prefixes.
///
/// Port of `metaCategoriesRule1`.
fn meta_categories_rule1(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    for ancestor in get_node_ancestors(doc, id, "div") {
        let elem_id = doc.id_attr(ancestor);
        let class = doc.class_name(ancestor);

        if starts_with(&class, "post-info")
            || starts_with(&class, "postinfo")
            || starts_with(&class, "post-meta")
            || starts_with(&class, "postmeta")
            || starts_with(&class, "meta")
            || starts_with(&class, "entry-meta")
            || starts_with(&class, "entry-info")
            || starts_with(&class, "entry-utility")
            || starts_with(&elem_id, "postpath")
        {
            return true;
        }
    }

    false
}

/// Matches `<a href>` inside p ancestors with postmeta/entry-categories class prefix.
///
/// Port of `metaCategoriesRule2`.
fn meta_categories_rule2(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    for ancestor in get_node_ancestors(doc, id, "p") {
        let elem_id = doc.id_attr(ancestor);
        let class = doc.class_name(ancestor);

        if starts_with(&class, "postmeta")
            || starts_with(&class, "entry-categories")
            || class == "postinfo"
            || elem_id == "filedunder"
        {
            return true;
        }
    }

    false
}

/// Matches `<a href>` inside footer ancestors with entry-meta/entry-footer class prefix.
///
/// Port of `metaCategoriesRule3`.
fn meta_categories_rule3(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    for ancestor in get_node_ancestors(doc, id, "footer") {
        let class = doc.class_name(ancestor);

        if starts_with(&class, "entry-meta") || starts_with(&class, "entry-footer") {
            return true;
        }
    }

    false
}

/// Matches `<a href>` inside li/span ancestors with post-category/cat-links class.
///
/// Port of `metaCategoriesRule4`.
fn meta_categories_rule4(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    let mut ancestors = get_node_ancestors(doc, id, "li");
    ancestors.extend(get_node_ancestors(doc, id, "span"));

    for ancestor in ancestors {
        let class = doc.class_name(ancestor);
        if class == "post-category"
            || class == "postcategory"
            || class == "entry-category"
            || contains(&class, "cat-links")
        {
            return true;
        }
    }

    false
}

/// Matches `<a href>` inside header ancestors with class "entry-header".
///
/// Port of `metaCategoriesRule5`.
fn meta_categories_rule5(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    for ancestor in get_node_ancestors(doc, id, "header") {
        if doc.class_name(ancestor) == "entry-header" {
            return true;
        }
    }

    false
}

/// Matches `<a href>` inside div ancestors with class "row" or "tags".
///
/// Port of `metaCategoriesRule6`.
fn meta_categories_rule6(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    for ancestor in get_node_ancestors(doc, id, "div") {
        let class = doc.class_name(ancestor);
        if class == "row" || class == "tags" {
            return true;
        }
    }

    false
}

// ---------------------------------------------------------------------------
// MetaTags rules
// ---------------------------------------------------------------------------

/// Matches `<a href>` inside div with class "tags".
///
/// Port of `metaTagsRule1`.
fn meta_tags_rule1(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    for ancestor in get_node_ancestors(doc, id, "div") {
        if doc.class_name(ancestor) == "tags" {
            return true;
        }
    }

    false
}

/// Matches `<a href>` inside p ancestors with "entry-tags" class prefix.
///
/// Port of `metaTagsRule2`.
fn meta_tags_rule2(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    for ancestor in get_node_ancestors(doc, id, "p") {
        if starts_with(&doc.class_name(ancestor), "entry-tags") {
            return true;
        }
    }

    false
}

/// Matches `<a href>` inside div ancestors with tag/meta-related classes.
///
/// Port of `metaTagsRule3`.
fn meta_tags_rule3(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    for ancestor in get_node_ancestors(doc, id, "div") {
        let class = doc.class_name(ancestor);
        if class == "row"
            || class == "jp-relatedposts"
            || class == "entry-utility"
            || starts_with(&class, "tag")
            || starts_with(&class, "postmeta")
            || starts_with(&class, "meta")
        {
            return true;
        }
    }

    false
}

/// Matches `<a href>` inside any ancestor with entry-meta, topics, or tags-links class.
///
/// Port of `metaTagsRule4`.
fn meta_tags_rule4(doc: &Document, id: NodeId) -> bool {
    if doc.tag_name(id) != "a" || doc.get_attribute(id, "href").is_none() {
        return false;
    }

    let mut cur = id;
    while let Some(parent) = doc.parent(cur) {
        let class = doc.class_name(parent);
        if class == "entry-meta" || contains(&class, "topics") || contains(&class, "tags-links") {
            return true;
        }
        cur = parent;
    }

    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dom::Document;
    use crate::selector::query;

    fn parse(html: &str) -> Document {
        Document::parse(html)
    }

    #[test]
    fn test_meta_author_rule1_rel_author() {
        let doc = parse(r#"<html><body><a rel="author">Author</a></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_AUTHOR).is_some());
    }

    #[test]
    fn test_meta_author_rule1_id_author() {
        let doc = parse(r#"<html><body><div id="author">Author Name</div></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_AUTHOR).is_some());
    }

    #[test]
    fn test_meta_author_rule2_class_author() {
        let doc = parse(r#"<html><body><span class="article-author">Jane</span></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_AUTHOR).is_some());
    }

    #[test]
    fn test_meta_author_discard_time() {
        let doc = parse(r#"<html><body><time>2024-01-01</time></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_AUTHOR_DISCARD).is_some());
    }

    #[test]
    fn test_meta_title_rule1_entry_title_h1() {
        let doc = parse(r#"<html><body><h1 class="entry-title">Title</h1></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_TITLE).is_some());
    }

    #[test]
    fn test_meta_title_rule2_exact_class() {
        let doc = parse(r#"<html><body><div class="post-title">My Post</div></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_TITLE).is_some());
    }

    #[test]
    fn test_meta_title_rule3_h2_title() {
        let doc = parse(r#"<html><body><h2 id="article-title">Headline</h2></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_TITLE).is_some());
    }

    #[test]
    fn test_meta_categories_rule1_post_meta_ancestor() {
        let doc = parse(
            r#"<html><body><div class="post-meta"><a href="/cat/news">News</a></div></body></html>"#,
        );
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_CATEGORIES).is_some());
    }

    #[test]
    fn test_meta_categories_rule4_cat_links() {
        let doc = parse(
            r#"<html><body><li class="cat-links"><a href="/category/tech">Tech</a></li></body></html>"#,
        );
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_CATEGORIES).is_some());
    }

    #[test]
    fn test_meta_tags_rule1_tags_div() {
        let doc = parse(
            r#"<html><body><div class="tags"><a href="/tag/rust">Rust</a></div></body></html>"#,
        );
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_TAGS).is_some());
    }

    #[test]
    fn test_meta_tags_rule4_entry_meta() {
        let doc = parse(
            r#"<html><body><div class="entry-meta"><a href="/tag/web">Web</a></div></body></html>"#,
        );
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_TAGS).is_some());
    }

    #[test]
    fn test_meta_author_no_match() {
        let doc = parse(r#"<html><body><p class="article-body">text</p></body></html>"#);
        let body = doc.body().unwrap();
        // Rule 3 is a last resort that catches "author" in class — not present here.
        assert!(query(&doc, body, META_AUTHOR).is_none());
    }

    #[test]
    fn test_meta_categories_rule1_no_href_rejected() {
        // <a> without href must not match even inside correct ancestor.
        let doc = parse(r#"<html><body><div class="post-meta"><a>No href</a></div></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_CATEGORIES).is_none());
    }

    #[test]
    fn test_meta_categories_rule1_wrong_ancestor_class() {
        // Correct tag ancestor but wrong class should not match.
        let doc =
            parse(r#"<html><body><div class="sidebar"><a href="/cat">Cat</a></div></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_CATEGORIES).is_none());
    }

    #[test]
    fn test_meta_tags_rule1_no_href_rejected() {
        // <a> without href must not match.
        let doc = parse(r#"<html><body><div class="tags"><a>No href</a></div></body></html>"#);
        let body = doc.body().unwrap();
        assert!(query(&doc, body, META_TAGS).is_none());
    }

    #[test]
    fn test_meta_tags_rule1_wrong_ancestor_class() {
        // tags-like ancestor but wrong class should not trigger rule1.
        let doc = parse(
            r#"<html><body><div class="sidebar"><a href="/tag/rust">Rust</a></div></body></html>"#,
        );
        let body = doc.body().unwrap();
        // rule3 would match "meta" but "sidebar" doesn't match tag/postmeta/meta either,
        // and there is no entry-meta/topics/tags-links ancestor for rule4.
        assert!(query(&doc, body, META_TAGS).is_none());
    }
}