meta_oxide 0.1.1

Universal metadata extraction library supporting 13 formats (HTML Meta, Open Graph, Twitter Cards, JSON-LD, Microdata, Microformats, RDFa, Dublin Core, Web App Manifest, oEmbed, rel-links, Images, SEO) with 7 language bindings
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
# MetaOxide Python API Reference

Complete API documentation for the Python package.

## Table of Contents

- [Installation]#installation
- [Core Classes]#core-classes
- [Extraction Methods]#extraction-methods
- [Data Types]#data-types
- [Exceptions]#exceptions
- [Type Hints]#type-hints

## Installation

```bash
pip install meta-oxide
```

## Core Classes

### `MetaOxide`

The main class for extracting metadata from HTML.

```python
class MetaOxide:
    """MetaOxide metadata extractor."""

    def __init__(self, html: str, base_url: str) -> None:
        """
        Initialize MetaOxide extractor.

        Args:
            html: HTML content to parse
            base_url: Base URL for resolving relative URLs

        Raises:
            MetaOxideError: If HTML parsing fails
            ValueError: If base_url is invalid

        Example:
            >>> from meta_oxide import MetaOxide
            >>> html = '<!DOCTYPE html>...'
            >>> extractor = MetaOxide(html, 'https://example.com')
        """
```

## Extraction Methods

### `extract_all()`

Extract all metadata formats at once.

```python
def extract_all(self) -> Dict[str, Any]:
    """
    Extract all metadata formats.

    Returns:
        Dictionary containing all extracted metadata

    Raises:
        MetaOxideError: If extraction fails

    Example:
        >>> metadata = extractor.extract_all()
        >>> print(metadata['title'])
        >>> print(metadata.get('description'))
    """
```

**Return Structure:**
```python
{
    'title': str,
    'description': str,
    'keywords': List[str],
    'author': str,
    'canonical': str,
    'og:title': str,
    'og:image': str,
    'twitter:card': str,
    # ... and more
}
```

### `extract_basic_meta()`

Extract basic HTML metadata.

```python
def extract_basic_meta(self) -> Dict[str, Any]:
    """
    Extract basic HTML metadata.

    Returns:
        Dictionary with title, description, keywords, etc.

    Example:
        >>> basic = extractor.extract_basic_meta()
        >>> print(basic['title'])
        >>> print(basic['description'])
    """
```

**Return Structure:**
```python
{
    'title': str,
    'description': str,
    'keywords': List[str],
    'author': str,
    'canonical': str,
    'charset': str,
    'viewport': str,
    'language': str,
    'robots': str
}
```

### `extract_opengraph()`

Extract Open Graph metadata.

```python
def extract_opengraph(self) -> Optional[Dict[str, Any]]:
    """
    Extract Open Graph metadata.

    Returns:
        Dictionary with Open Graph data or None

    Example:
        >>> og = extractor.extract_opengraph()
        >>> if og:
        ...     print(og['title'])
        ...     print(og['image'])
    """
```

**Return Structure:**
```python
{
    'title': str,
    'type': str,
    'image': str,
    'url': str,
    'description': str,
    'site_name': str,
    'locale': str,
    'audio': str,
    'video': str
}
```

### `extract_twitter_card()`

Extract Twitter Card metadata.

```python
def extract_twitter_card(self) -> Optional[Dict[str, Any]]:
    """
    Extract Twitter Card metadata.

    Returns:
        Dictionary with Twitter Card data or None

    Example:
        >>> twitter = extractor.extract_twitter_card()
        >>> if twitter:
        ...     print(twitter['card'])
        ...     print(twitter['title'])
    """
```

**Return Structure:**
```python
{
    'card': str,
    'site': str,
    'creator': str,
    'title': str,
    'description': str,
    'image': str,
    'image:alt': str
}
```

### `extract_jsonld()`

Extract JSON-LD structured data.

```python
def extract_jsonld(self) -> List[Dict[str, Any]]:
    """
    Extract JSON-LD structured data.

    Returns:
        List of JSON-LD objects

    Example:
        >>> jsonld = extractor.extract_jsonld()
        >>> for item in jsonld:
        ...     print(item.get('@type'))
        ...     print(item.get('name'))
    """
```

### `extract_microdata()`

Extract Microdata (schema.org).

```python
def extract_microdata(self) -> List[Dict[str, Any]]:
    """
    Extract Microdata items.

    Returns:
        List of Microdata items

    Example:
        >>> microdata = extractor.extract_microdata()
        >>> for item in microdata:
        ...     print(item['type'])
        ...     print(item['properties'])
    """
```

**Item Structure:**
```python
{
    'type': List[str],
    'properties': Dict[str, List[Any]],
    'id': Optional[str]
}
```

### `extract_microformats()`

Extract Microformats data.

```python
def extract_microformats(self) -> Dict[str, List[Dict[str, Any]]]:
    """
    Extract all Microformats.

    Returns:
        Dictionary mapping format types to items

    Example:
        >>> mf = extractor.extract_microformats()
        >>> if 'h-card' in mf:
        ...     for card in mf['h-card']:
        ...         print(card['name'])
    """
```

**Return Structure:**
```python
{
    'h-card': List[Dict],
    'h-entry': List[Dict],
    'h-event': List[Dict],
    'h-review': List[Dict],
    'h-recipe': List[Dict],
    'h-product': List[Dict]
}
```

### `extract_dublin_core()`

Extract Dublin Core metadata.

```python
def extract_dublin_core(self) -> Optional[Dict[str, str]]:
    """
    Extract Dublin Core metadata.

    Returns:
        Dictionary with Dublin Core data or None

    Example:
        >>> dc = extractor.extract_dublin_core()
        >>> if dc:
        ...     print(dc['title'])
        ...     print(dc['creator'])
    """
```

### `extract_rdfa()`

Extract RDFa triples.

```python
def extract_rdfa(self) -> List[Dict[str, str]]:
    """
    Extract RDFa triples.

    Returns:
        List of RDFa triple dictionaries

    Example:
        >>> rdfa = extractor.extract_rdfa()
        >>> for triple in rdfa:
        ...     print(f"{triple['subject']} {triple['predicate']} {triple['object']}")
    """
```

### `extract_rel_links()`

Extract link relations.

```python
def extract_rel_links(self) -> Dict[str, List[Dict[str, str]]]:
    """
    Extract link relations.

    Returns:
        Dictionary mapping rel types to links

    Example:
        >>> links = extractor.extract_rel_links()
        >>> if 'canonical' in links:
        ...     print(links['canonical'][0]['href'])
    """
```

### `extract_manifest()`

Extract web app manifest.

```python
def extract_manifest(self) -> Optional[Dict[str, Any]]:
    """
    Extract web app manifest data.

    Returns:
        Manifest dictionary or None

    Example:
        >>> manifest = extractor.extract_manifest()
        >>> if manifest:
        ...     print(manifest['name'])
        ...     print(manifest['icons'])
    """
```

## Data Types

### Microformats Types

#### h-card (Person/Organization)

```python
{
    'name': str,
    'url': str,
    'photo': str,
    'email': str,
    'tel': str,
    'org': str,
    'adr': Dict[str, str]
}
```

#### h-entry (Blog Post/Article)

```python
{
    'name': str,
    'author': Dict,  # h-card
    'published': str,
    'updated': str,
    'content': str,
    'summary': str,
    'url': str,
    'category': List[str],
    'syndication': List[str]
}
```

#### h-event (Event)

```python
{
    'name': str,
    'start': str,
    'end': str,
    'duration': str,
    'summary': str,
    'description': str,
    'url': str,
    'location': str,
    'category': List[str]
}
```

## Exceptions

### `MetaOxideError`

Base exception class for MetaOxide errors.

```python
class MetaOxideError(Exception):
    """Base exception for MetaOxide errors."""
    pass
```

### `ParseError`

Raised when HTML parsing fails.

```python
class ParseError(MetaOxideError):
    """HTML parsing error."""
    pass
```

### `ExtractionError`

Raised when metadata extraction fails.

```python
class ExtractionError(MetaOxideError):
    """Metadata extraction error."""
    pass
```

### `UrlError`

Raised when URL parsing or resolution fails.

```python
class UrlError(MetaOxideError):
    """URL parsing error."""
    pass
```

### Exception Handling Example

```python
from meta_oxide import MetaOxide, MetaOxideError, ParseError

try:
    extractor = MetaOxide(html, url)
    metadata = extractor.extract_all()
except ParseError as e:
    print(f"HTML parsing failed: {e}")
except MetaOxideError as e:
    print(f"Extraction error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

## Type Hints

Full type hint support for better IDE experience:

```python
from typing import Dict, List, Optional, Any
from meta_oxide import MetaOxide

def extract_metadata(html: str, url: str) -> Dict[str, Any]:
    """Extract metadata with type hints."""
    extractor: MetaOxide = MetaOxide(html, url)
    metadata: Dict[str, Any] = extractor.extract_all()
    return metadata

def extract_opengraph(html: str, url: str) -> Optional[Dict[str, Any]]:
    """Extract Open Graph with type hints."""
    extractor: MetaOxide = MetaOxide(html, url)
    og_data: Optional[Dict[str, Any]] = extractor.extract_opengraph()
    return og_data
```

## Async Support

MetaOxide works seamlessly with async Python:

```python
import asyncio
import aiohttp
from meta_oxide import MetaOxide

async def extract_from_url(url: str) -> Dict[str, Any]:
    """Async extraction from URL."""
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            html = await response.text()
            extractor = MetaOxide(html, url)
            return extractor.extract_all()

async def main():
    metadata = await extract_from_url('https://example.com')
    print(metadata)

asyncio.run(main())
```

## Performance Tips

### Batch Processing

```python
from concurrent.futures import ThreadPoolExecutor
from meta_oxide import MetaOxide

def extract_metadata(html: str, url: str) -> Dict[str, Any]:
    extractor = MetaOxide(html, url)
    return extractor.extract_all()

# Process multiple documents in parallel
urls = ['url1', 'url2', 'url3']
htmls = [fetch_html(url) for url in urls]

with ThreadPoolExecutor(max_workers=4) as executor:
    results = list(executor.map(extract_metadata, htmls, urls))
```

### Selective Extraction

Extract only what you need for better performance:

```python
# Instead of extract_all()
metadata = extractor.extract_all()

# Extract only specific formats
og = extractor.extract_opengraph()
twitter = extractor.extract_twitter_card()
```

### Caching

```python
from functools import lru_cache

@lru_cache(maxsize=128)
def extract_metadata_cached(url: str) -> Dict[str, Any]:
    html = fetch_html(url)
    extractor = MetaOxide(html, url)
    return extractor.extract_all()
```

## Context Manager Support

```python
# Future API (if implemented)
with MetaOxide(html, url) as extractor:
    metadata = extractor.extract_all()
# Automatic cleanup
```

## See Also

- [Getting Started Guide]/docs/getting-started/getting-started-python.md
- [Flask Integration]/docs/integrations/flask-integration.md
- [Django Integration]/docs/integrations/django-integration.md
- [Examples]/examples/real-world/python-flask-api/