halldyll-parser 0.1.0

HTML/CSS parsing and content extraction for halldyll 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
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
//! # halldyll-parser
//!
//! High-performance HTML parsing and content extraction library.
//!
//! ## Features
//!
//! - **Metadata extraction**: Title, description, OpenGraph, Twitter Cards, robots, JSON-LD
//! - **Content extraction**: Headings, paragraphs, lists, tables, code blocks, quotes
//! - **Link analysis**: Internal/external classification, nofollow detection, URL resolution
//! - **Image extraction**: With lazy loading, srcset, and accessibility info
//! - **Text processing**: Boilerplate removal, readability scoring, language detection
//! - **Structured data**: JSON-LD and Microdata extraction
//!
//! ## Quick Start
//!
//! ```rust
//! use halldyll_parser::{HtmlParser, parse};
//!
//! // Quick parse
//! let html = "<html><head><title>Test</title></head><body><p>Hello</p></body></html>";
//! let result = parse(html).unwrap();
//! println!("Title: {:?}", result.metadata.title);
//!
//! // With base URL for resolving relative links
//! let parser = HtmlParser::with_base_url("https://example.com").unwrap();
//! let result = parser.parse(html).unwrap();
//! ```
//!
//! ## Architecture
//!
//! This crate is organized into focused modules:
//! - `types`: All type definitions
//! - `selector`: CSS selector utilities and caching
//! - `metadata`: Metadata extraction (OG, Twitter, robots, etc.)
//! - `text`: Text extraction and processing
//! - `links`: Link extraction and analysis
//! - `content`: Structured content extraction (headings, lists, tables, etc.)
//! - `parser`: Main HtmlParser API

// ============================================================================
// MODULE DECLARATIONS
// ============================================================================

pub mod types;
pub mod selector;
pub mod metadata;
pub mod text;
pub mod links;
pub mod content;
pub mod parser;

// Advanced extraction modules
pub mod forms;
pub mod pagination;
pub mod contact;
pub mod feeds;
pub mod fingerprint;

// Legacy module alias
pub mod selectors;

// ============================================================================
// PUBLIC RE-EXPORTS
// ============================================================================

// Types
pub use types::{
    // Errors
    ParserError, ParserResult,
    
    // Text content
    TextContent,
    
    // Headings
    Heading,
    
    // Links
    Link, LinkRel, LinkType,
    
    // Images
    Image, ImageLoading,
    
    // Lists
    ListContent, ListType, ListItem,
    
    // Tables
    TableContent, TableRow, TableCell,
    
    // Code
    CodeBlock,
    
    // Quotes
    Quote,
    
    // Metadata
    PageMetadata, OpenGraph, TwitterCard, RobotsMeta, AlternateLink,
    
    // Structured data
    StructuredData, StructuredDataFormat,
    
    // Parsed content
    ParsedContent, ParseStats,
    
    // Configuration
    ParserConfig,
    
    // Helper functions
    normalize_whitespace, clean_text, truncate_text,
};

// Selector utilities
pub use selector::{
    SELECTORS, CachedSelectors,
    get_or_create_selector, parse_selector, try_parse_selector,
    heading_selector,
    CONTENT_SELECTORS, BOILERPLATE_SELECTORS,
    attr_selector, class_selector, id_selector,
    meta_name_selector, meta_property_selector, link_rel_selector,
};

// Metadata extraction
pub use metadata::{
    extract_metadata,
    extract_title, extract_charset, extract_language,
    extract_meta_content, extract_keywords,
    extract_canonical, extract_favicon,
    extract_robots,
    extract_opengraph, extract_twitter_card,
    extract_alternates,
    extract_structured_data, extract_json_ld, extract_microdata,
};

// Text extraction
pub use text::{
    extract_text as extract_text_content,
    normalize_text, strip_html_tags,
    count_words, count_sentences,
    flesch_reading_ease, flesch_kincaid_grade,
    detect_language,
    is_inline_element,
};

// Link extraction
pub use links::{
    extract_links, extract_link,
    resolve_url, normalize_url,
    parse_rel_attribute, is_nofollow, is_sponsored, is_ugc,
    filter_internal_links, filter_external_links, filter_followable_links,
    get_external_domains, calculate_link_stats, LinkStats,
};

// Content extraction
pub use content::{
    extract_headings, get_main_heading, build_outline, OutlineItem,
    extract_paragraphs,
    extract_lists,
    extract_tables,
    extract_code_blocks,
    extract_quotes,
    extract_images,
};

// Parser
pub use parser::{
    HtmlParser,
    parse, parse_with_url,
    get_metadata, get_text, get_links,
};

// Forms extraction
pub use forms::{
    Form, FormField, FormType, FieldType, FormMethod, SelectOption,
    extract_forms,
    has_forms, has_login_form, has_search_form,
    get_login_forms, get_search_forms, get_contact_forms,
};

// Pagination extraction
pub use pagination::{
    Pagination, PageUrl, PaginationType,
    extract_pagination, has_pagination,
    get_next_page, get_prev_page,
};

// Contact info extraction
pub use contact::{
    ContactInfo, Email, EmailSource, Phone, PhoneType,
    Address, Coordinates, SocialLink, SocialPlatform,
    extract_contact_info, extract_emails, extract_phones,
    extract_addresses, extract_social_links,
    has_contact_info, get_emails, get_phones, get_social_links,
};

// Feeds and sitemaps extraction
pub use feeds::{
    FeedInfo, Feed, FeedType, Sitemap, SitemapType, SitemapSource,
    extract_feed_info, has_feeds, get_rss_feed, get_atom_feed, get_feed, get_sitemap,
};

// Content fingerprinting and AMP
pub use fingerprint::{
    ContentFingerprint, AmpInfo, CacheHints,
    generate_fingerprint, fingerprint_document,
    extract_amp_info, extract_cache_hints,
    has_content_changed, content_similarity, is_amp_page, get_amp_url, quick_hash,
};

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_basic_parse() {
        let html = r#"
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <title>Test Page</title>
                <meta name="description" content="Test description">
            </head>
            <body>
                <h1>Main Title</h1>
                <p>This is a test paragraph with enough content.</p>
                <a href="/link">Internal link</a>
            </body>
            </html>
        "#;

        let result = parse(html).unwrap();

        assert_eq!(result.metadata.title, Some("Test Page".to_string()));
        assert_eq!(result.metadata.description, Some("Test description".to_string()));
        assert!(!result.headings.is_empty());
        assert!(!result.paragraphs.is_empty());
        assert!(!result.links.is_empty());
    }

    #[test]
    fn test_parse_with_base_url() {
        let html = r#"
            <html>
            <body>
                <a href="/page">Link</a>
                <img src="/image.jpg" alt="Image">
            </body>
            </html>
        "#;

        let result = parse_with_url(html, "https://example.com").unwrap();

        // Links should be resolved
        let link = &result.links[0];
        assert_eq!(link.url, Some("https://example.com/page".to_string()));

        // Images should be resolved
        let img = &result.images[0];
        assert_eq!(img.url, Some("https://example.com/image.jpg".to_string()));
    }

    #[test]
    fn test_metadata_extraction() {
        let html = r#"
            <html>
            <head>
                <title>Title</title>
                <meta property="og:title" content="OG Title">
                <meta name="twitter:card" content="summary">
                <meta name="robots" content="noindex, nofollow">
            </head>
            </html>
        "#;

        let metadata = get_metadata(html).unwrap();

        assert!(metadata.opengraph.is_present());
        assert!(metadata.twitter.is_present());
        assert!(!metadata.robots.index);
        assert!(!metadata.robots.follow);
    }

    #[test]
    fn test_text_extraction() {
        let html = r#"
            <html>
            <body>
                <nav>Skip this navigation</nav>
                <article>
                    <p>This is the main content that should be extracted.</p>
                </article>
                <footer>Skip this footer</footer>
            </body>
            </html>
        "#;

        let text = get_text(html).unwrap();

        assert!(text.cleaned_text.contains("main content"));
        assert!(text.word_count > 0);
    }

    #[test]
    fn test_link_extraction() {
        let html = r#"
            <html>
            <body>
                <a href="https://internal.com/page">Internal</a>
                <a href="https://external.com" rel="nofollow">External</a>
            </body>
            </html>
        "#;

        let parser = HtmlParser::with_base_url("https://internal.com").unwrap();
        let links = parser.extract_links(html).unwrap();

        assert_eq!(links.len(), 2);

        let internal = links.iter().find(|l| l.text == "Internal").unwrap();
        assert_eq!(internal.link_type, LinkType::Internal);

        let external = links.iter().find(|l| l.text == "External").unwrap();
        assert_eq!(external.link_type, LinkType::External);
        assert!(external.is_nofollow);
    }

    #[test]
    fn test_structured_data() {
        let html = r#"
            <html>
            <head>
                <script type="application/ld+json">
                {
                    "@context": "https://schema.org",
                    "@type": "Article",
                    "headline": "Test Article"
                }
                </script>
            </head>
            </html>
        "#;

        let result = parse(html).unwrap();

        assert!(result.has_structured_data());
        assert_eq!(result.structured_data[0].schema_type, Some("Article".to_string()));
    }

    #[test]
    fn test_content_extraction() {
        let html = r#"
            <html>
            <body>
                <h1 id="main">Main Heading</h1>
                <p>Paragraph with enough content to pass filter.</p>
                <ul>
                    <li>Item 1</li>
                    <li>Item 2</li>
                </ul>
                <table>
                    <tr><th>Header</th></tr>
                    <tr><td>Data</td></tr>
                </table>
                <pre><code class="language-rust">fn main() {}</code></pre>
                <blockquote>A quote</blockquote>
            </body>
            </html>
        "#;

        let result = parse(html).unwrap();

        assert!(!result.headings.is_empty());
        assert_eq!(result.headings[0].id, Some("main".to_string()));

        assert!(!result.paragraphs.is_empty());
        assert!(!result.lists.is_empty());
        assert!(!result.tables.is_empty());
        assert!(!result.code_blocks.is_empty());
        assert!(!result.quotes.is_empty());
    }

    #[test]
    fn test_html_parser_api() {
        let parser = HtmlParser::new();

        assert!(!parser.has_base_url());

        let mut parser2 = HtmlParser::new();
        parser2.set_base_url("https://example.com").unwrap();
        assert!(parser2.has_base_url());

        let parser3 = HtmlParser::with_config(ParserConfig::minimal());
        assert!(!parser3.config().extract_images);
    }

    #[test]
    fn test_selector_utilities() {
        // Pre-compiled selectors should work
        let _ = &SELECTORS.h1;
        let _ = &SELECTORS.body;

        // Dynamic selectors should work
        let sel = parse_selector("div.test").unwrap();
        assert!(sel.matches(&scraper::Html::parse_fragment("<div class='test'></div>")
            .select(&sel).next().unwrap()));
    }

    #[test]
    fn test_readability_scoring() {
        let simple = "The cat sat on the mat. The dog ran fast.";
        let score = flesch_reading_ease(simple);
        assert!(score > 60.0); // Should be easy to read
    }

    #[test]
    fn test_language_detection() {
        let english = "The quick brown fox jumps over the lazy dog.";
        assert_eq!(detect_language(english), Some("en".to_string()));

        let french = "Le chat est sur la table dans la maison.";
        assert_eq!(detect_language(french), Some("fr".to_string()));
    }

    #[test]
    fn test_normalize_whitespace() {
        let text = "  Hello   world  \n\n  test  ";
        let normalized = normalize_whitespace(text);
        assert_eq!(normalized, "Hello world test");
    }

    #[test]
    fn test_parse_stats() {
        let html = "<html><body><p>Test</p></body></html>";
        let result = parse(html).unwrap();

        assert!(result.stats.html_size > 0);
        assert!(result.stats.node_count > 0);
        assert!(result.stats.parse_time_us > 0);
    }
}