crawl-any-website 0.1.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- crawl_any_website-0.1.2/LICENSE +21 -0
- crawl_any_website-0.1.2/PKG-INFO +355 -0
- crawl_any_website-0.1.2/README.md +341 -0
- crawl_any_website-0.1.2/crawl/__init__.py +35 -0
- crawl_any_website-0.1.2/crawl/cleaner.py +194 -0
- crawl_any_website-0.1.2/crawl/cli.py +73 -0
- crawl_any_website-0.1.2/crawl/crawler.py +216 -0
- crawl_any_website-0.1.2/crawl/dom.py +196 -0
- crawl_any_website-0.1.2/crawl/downloader.py +264 -0
- crawl_any_website-0.1.2/crawl/exceptions.py +65 -0
- crawl_any_website-0.1.2/crawl/exporter.py +137 -0
- crawl_any_website-0.1.2/crawl/extractor.py +377 -0
- crawl_any_website-0.1.2/crawl/parser.py +103 -0
- crawl_any_website-0.1.2/crawl/selector.py +233 -0
- crawl_any_website-0.1.2/crawl/tokenizer.py +343 -0
- crawl_any_website-0.1.2/crawl/utils.py +79 -0
- crawl_any_website-0.1.2/crawl/version.py +8 -0
- crawl_any_website-0.1.2/crawl_any_website.egg-info/PKG-INFO +355 -0
- crawl_any_website-0.1.2/crawl_any_website.egg-info/SOURCES.txt +30 -0
- crawl_any_website-0.1.2/crawl_any_website.egg-info/dependency_links.txt +1 -0
- crawl_any_website-0.1.2/crawl_any_website.egg-info/entry_points.txt +2 -0
- crawl_any_website-0.1.2/crawl_any_website.egg-info/top_level.txt +1 -0
- crawl_any_website-0.1.2/pyproject.toml +26 -0
- crawl_any_website-0.1.2/setup.cfg +4 -0
- crawl_any_website-0.1.2/tests/test_cleaner.py +93 -0
- crawl_any_website-0.1.2/tests/test_dom.py +80 -0
- crawl_any_website-0.1.2/tests/test_downloader.py +83 -0
- crawl_any_website-0.1.2/tests/test_exporter.py +88 -0
- crawl_any_website-0.1.2/tests/test_extractor.py +185 -0
- crawl_any_website-0.1.2/tests/test_parser.py +82 -0
- crawl_any_website-0.1.2/tests/test_selector.py +95 -0
- crawl_any_website-0.1.2/tests/test_tokenizer.py +82 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vrushabh Hirap
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: crawl-any-website
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: A production-quality web crawling and HTML parsing engine built completely from scratch.
|
|
5
|
+
Author: Vrushabh Hirap
|
|
6
|
+
License: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# Crawl: Scratch-built HTML Parser & Web Crawling Engine
|
|
16
|
+
|
|
17
|
+
`crawl` is a production-quality, dependency-free Python library built entirely from scratch. It implements its own lexical tokenizer, tree construction parser, Document Object Model (DOM), CSS selector search engine, structured data extractor, HTML cleaner, and multi-format exporters.
|
|
18
|
+
|
|
19
|
+
This engine does not wrap third-party libraries like BeautifulSoup, lxml, Scrapy, Selenium, or Playwright. Instead, it serves as a pure demonstration of browser-like parsing and scraping internals using Python's standard library.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Table of Contents
|
|
24
|
+
1. [Installation](#installation)
|
|
25
|
+
2. [Technical Architecture](#technical-architecture)
|
|
26
|
+
3. [API Reference](#api-reference)
|
|
27
|
+
- [Crawl](#crawl)
|
|
28
|
+
- [Page](#page)
|
|
29
|
+
- [Node](#node)
|
|
30
|
+
- [Response](#response)
|
|
31
|
+
- [Exceptions](#exceptions)
|
|
32
|
+
4. [Usage Recipes](#usage-recipes)
|
|
33
|
+
- [Recipe 1: Local HTML Parsing & CSS Querying](#recipe-1-local-html-parsing--css-querying)
|
|
34
|
+
- [Recipe 2: Live Crawling with Redirect History](#recipe-2-live-crawling-with-redirect-history)
|
|
35
|
+
- [Recipe 3: Extracting Tables & Forms](#recipe-3-extracting-tables--forms)
|
|
36
|
+
- [Recipe 4: Decoupled Parsing, Cleaning, & Exporting](#recipe-4-decoupled-parsing-cleaning--exporting)
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
You can install the package in several ways:
|
|
43
|
+
|
|
44
|
+
### 1. Install from PyPI
|
|
45
|
+
```bash
|
|
46
|
+
pip install crawl-any-website
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 2. Developer Editable Mode (Recommended)
|
|
50
|
+
From the root directory of this repository, run:
|
|
51
|
+
```bash
|
|
52
|
+
pip install -e .
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### 3. Standard Local Installation
|
|
56
|
+
```bash
|
|
57
|
+
pip install .
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 4. Direct GitHub Installation (For other users)
|
|
61
|
+
```bash
|
|
62
|
+
pip install git+https://github.com/vrushabh-hirap/crawl.git
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Technical Architecture
|
|
68
|
+
|
|
69
|
+
The library is decoupled into distinct, modular subsystems:
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
┌──────────────┐
|
|
73
|
+
│ Downloader │
|
|
74
|
+
└──────┬───────┘
|
|
75
|
+
│ HTTP Response
|
|
76
|
+
▼
|
|
77
|
+
┌──────────────┐
|
|
78
|
+
│ Tokenizer │
|
|
79
|
+
└──────┬───────┘
|
|
80
|
+
│ Token Stream
|
|
81
|
+
▼
|
|
82
|
+
┌──────────────┐
|
|
83
|
+
│ Parser │
|
|
84
|
+
└──────┬───────┘
|
|
85
|
+
│ DOM Tree
|
|
86
|
+
▼
|
|
87
|
+
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
|
|
88
|
+
│ Selector │◄───────►│ DOM Node │◄───────►│ Extractor │
|
|
89
|
+
└──────────────┘ └──────┬───────┘ └──────────────┘
|
|
90
|
+
│ In-Place Cleanup
|
|
91
|
+
▼
|
|
92
|
+
┌──────────────┐ ┌──────────────┐
|
|
93
|
+
│ Cleaner ├────────►│ Exporter │
|
|
94
|
+
└──────────────┘ └──────────────┘
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
1. **Downloader (`downloader.py`)**: Uses Python's built-in `urllib.request` HTTPS handlers to negotiate request headers, enforce timeouts, handle redirects, capture redirect hop chains, and configure SSL/TLS verification contexts.
|
|
98
|
+
2. **Lexical Tokenizer (`tokenizer.py`)**: A character-by-character scanner implemented as a state machine. It converts raw markup text into discrete tags (`START_TAG`, `END_TAG`), character arrays (`TEXT`), docstrings (`DOCTYPE`), and comment blocks (`COMMENT`).
|
|
99
|
+
3. **DOM Parser (`parser.py`)**: A stack-based builder that processes the token stream. It auto-closes unclosed nested tags based on parent tags and skips standard HTML void elements (such as `img`, `br`, `hr`, `input`, `meta`, `link`).
|
|
100
|
+
4. **DOM Tree (`dom.py`)**: Represents elements, text blocks, comment lines, and doctype markers as `Node` structures. Supports DOM tree navigation (`append_child`, `remove_child`) and serialization (`inner_html`, `outer_html`).
|
|
101
|
+
5. **Selector Engine (`selector.py`)**: Evaluates CSS queries left-to-right, processing tags, IDs, class names, descendant spacing, direct children (`>`), and comma lists, keeping nodes sorted in document pre-order.
|
|
102
|
+
6. **Data Extractor (`extractor.py`)**: Isolates headers, paragraphs, titles, tables, forms, list items, links, and buttons, automatically resolving relative paths.
|
|
103
|
+
7. **DOM Cleaner (`cleaner.py`)**: Collapses multiple whitespaces, decodes HTML entities, prunes empty nodes (ignoring void tags), and removes identical sibling subtrees.
|
|
104
|
+
8. **Exporter (`exporter.py`)**: Outputs raw data arrays to structured CSV, JSON, or TXT formats.
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## API Reference
|
|
109
|
+
|
|
110
|
+
### `Crawl`
|
|
111
|
+
The high-level user interface responsible for executing network transfers and returning parsed results.
|
|
112
|
+
|
|
113
|
+
* **Constructor**:
|
|
114
|
+
```python
|
|
115
|
+
from crawl import Crawl
|
|
116
|
+
crawler = Crawl(
|
|
117
|
+
default_headers: dict = None, # Merged with standard request headers
|
|
118
|
+
timeout: float = 10.0, # Connection timeout in seconds
|
|
119
|
+
verify_ssl: bool = True, # Toggles SSL certificate verification
|
|
120
|
+
rate_limit_delay: float = 0.0, # Delay (in seconds) between requests
|
|
121
|
+
obey_robots: bool = False # Respect robots.txt directives (extension placeholder)
|
|
122
|
+
)
|
|
123
|
+
```
|
|
124
|
+
* **Methods**:
|
|
125
|
+
* **`fetch(url: str, headers: dict = None, timeout: float = None) -> Page`**: Downloads the target URL, parses its content, and returns a `Page` object.
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
### `Page`
|
|
130
|
+
Returned by `Crawl.fetch()`. It represents a downloaded, parsed HTML document.
|
|
131
|
+
|
|
132
|
+
* **Properties**:
|
|
133
|
+
* **`url`**: The final absolute URL of the page (after redirects) *(type: `str`)*.
|
|
134
|
+
* **`response`**: The raw network response object *(type: `Response`)*.
|
|
135
|
+
* **`node`**: The document's root Node *(type: `Node`)*.
|
|
136
|
+
* **Extraction Methods**:
|
|
137
|
+
* **`title() -> str`**: Gets the page title (falls back to the first `<h1>` text if missing).
|
|
138
|
+
* **`paragraphs() -> List[str]`**: Gets the text of all `<p>` paragraph tags.
|
|
139
|
+
* **`images() -> List[str]`**: Gets absolute URLs of all `<img>` src paths.
|
|
140
|
+
* **`links() -> List[str]`**: Gets absolute URLs of all `<a>` anchor href paths.
|
|
141
|
+
* **`tables() -> List[List[List[str]]]`**: Gets row/column contents for all tables on the page.
|
|
142
|
+
* **`forms() -> List[Dict[str, Any]]`**: Gets metadata for all form actions, methods, and inputs.
|
|
143
|
+
* **`lists() -> List[List[str]]`**: Gets list items (`<li>`) grouped by parent list (`<ul>`/`<ol>`).
|
|
144
|
+
* **`buttons() -> List[Dict[str, str]]`**: Gets button nodes and button-type inputs (submit, reset).
|
|
145
|
+
* **`meta_tags() -> List[Dict[str, str]]`**: Gets meta name, property, and content descriptors.
|
|
146
|
+
* **`headers() -> List[Dict[str, str]]`**: Gets headings (H1–H6) in document order.
|
|
147
|
+
* **DOM & Traversal Methods**:
|
|
148
|
+
* **`find(selector: str) -> Optional[Node]`**: Returns the first node matching the CSS selector.
|
|
149
|
+
* **`find_all(selector: str) -> List[Node]`**: Returns all nodes matching the CSS selector.
|
|
150
|
+
* **`get_text() -> str`**: Returns raw concatenated text content of the entire document.
|
|
151
|
+
* **`inner_html() -> str`**: Returns the serialized inner HTML of the document's children.
|
|
152
|
+
* **`outer_html() -> str`**: Returns the serialized outer HTML of the full DOM tree.
|
|
153
|
+
* **Cleaning & Export Methods**:
|
|
154
|
+
* **`clean() -> None`**: Performs full DOM whitespace normalization, entity decoding, and duplicate sibling pruning in-place.
|
|
155
|
+
* **`export_json(filepath: str) -> None`**: Exports basic page metadata to a local JSON file.
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
### `Node`
|
|
160
|
+
A class representing a single element, text node, comment, or doctype.
|
|
161
|
+
|
|
162
|
+
* **Properties**:
|
|
163
|
+
* **`tag`**: Tag name in lowercase (e.g. `'div'`), or `None` for text nodes, or `#comment`/`#doctype` *(type: `Optional[str]`)*.
|
|
164
|
+
* **`attributes`**: Attribute key-value mapping (lowercased keys) *(type: `dict`)*.
|
|
165
|
+
* **`children`**: List of child DOM nodes *(type: `List[Node]`)*.
|
|
166
|
+
* **`parent`**: Parent element node, or `None` if it is a root *(type: `Optional[Node]`)*.
|
|
167
|
+
* **`text`**: Raw text content (used for text, comment, and doctype nodes) *(type: `Optional[str]`)*.
|
|
168
|
+
* **Methods**:
|
|
169
|
+
* **`append_child(child: Node) -> None`**: Appends a child Node, managing parent links.
|
|
170
|
+
* **`remove_child(child: Node) -> None`**: Removes a child Node.
|
|
171
|
+
* **`get_attribute(name: str, default: str = None) -> Optional[str]`**: Case-insensitive attribute lookup.
|
|
172
|
+
* **`set_attribute(name: str, value: str) -> None`**: Sets or overrides a custom attribute.
|
|
173
|
+
* **`find(selector: str) -> Optional[Node]`**: Performs CSS selector lookup starting from this node.
|
|
174
|
+
* **`find_all(selector: str) -> List[Node]`**: Performs descendant CSS selector lookup.
|
|
175
|
+
* **`get_text() -> str`**: Returns recursive text inside this Node.
|
|
176
|
+
* **`inner_html() -> str`**: Serializes HTML contents of this Node's children.
|
|
177
|
+
* **`outer_html() -> str`**: Serializes the HTML structure of this node and its children.
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
### `Response`
|
|
182
|
+
Represents the result of an HTTP transaction.
|
|
183
|
+
|
|
184
|
+
* **Properties**:
|
|
185
|
+
* **`url`**: Final landing URL (after resolving redirects) *(type: `str`)*.
|
|
186
|
+
* **`status_code`**: HTTP status response code (e.g., `200`, `404`) *(type: `int`)*.
|
|
187
|
+
* **`headers`**: Dictionary of case-insensitive response headers *(type: `dict`)*.
|
|
188
|
+
* **`content`**: Raw binary content *(type: `bytes`)*.
|
|
189
|
+
* **`text`**: Decoded content string (automatically parses charset from headers) *(type: `str`)*.
|
|
190
|
+
* **`redirect_history`**: List of redirect hops: `[{'status': int, 'url': str, 'headers': dict}]` *(type: `List[dict]`)*.
|
|
191
|
+
|
|
192
|
+
---
|
|
193
|
+
|
|
194
|
+
### Exceptions
|
|
195
|
+
|
|
196
|
+
* **`CrawlError`**: Base exception class.
|
|
197
|
+
* **`DownloadError`**: Connection issues, timeouts, or SSL failures.
|
|
198
|
+
* **`ParserError`**: Unrecoverable syntax errors during tokenization or parsing.
|
|
199
|
+
* **`InvalidSelector`**: Invalid CSS selector structure.
|
|
200
|
+
* **`NodeNotFound`**: Missing node during critical DOM traversals.
|
|
201
|
+
* **`ExportError`**: File writing or serialization constraints failures.
|
|
202
|
+
|
|
203
|
+
---
|
|
204
|
+
|
|
205
|
+
## Usage Recipes
|
|
206
|
+
|
|
207
|
+
### Recipe 1: Local HTML Parsing & CSS Querying
|
|
208
|
+
You can parse a string of HTML and query elements directly using CSS selectors.
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
from crawl.parser import parse_html
|
|
212
|
+
|
|
213
|
+
html_content = """
|
|
214
|
+
<div id="container">
|
|
215
|
+
<h1 class="title">Product Catalog</h1>
|
|
216
|
+
<ul class="items">
|
|
217
|
+
<li class="item" id="p-1">Laptop <span class="badge">Sale</span></li>
|
|
218
|
+
<li class="item" id="p-2">Phone</li>
|
|
219
|
+
</ul>
|
|
220
|
+
</div>
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
# 1. Parse string to DOM Node
|
|
224
|
+
root = parse_html(html_content)
|
|
225
|
+
|
|
226
|
+
# 2. Query by ID
|
|
227
|
+
container = root.find("#container")
|
|
228
|
+
print("Container ID attribute:", container.get_attribute("id"))
|
|
229
|
+
|
|
230
|
+
# 3. Query by Class
|
|
231
|
+
title_node = root.find(".title")
|
|
232
|
+
print("Title Text:", title_node.get_text())
|
|
233
|
+
|
|
234
|
+
# 4. Direct Child Selector (ul > li)
|
|
235
|
+
list_items = root.find_all("ul.items > li")
|
|
236
|
+
for item in list_items:
|
|
237
|
+
print(f"Item text: {item.get_text()} | ID: {item.get_attribute('id')}")
|
|
238
|
+
|
|
239
|
+
# 5. Descendant Selector (div span)
|
|
240
|
+
badges = root.find_all("div .badge")
|
|
241
|
+
for badge in badges:
|
|
242
|
+
print("Found badge:", badge.get_text())
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
### Recipe 2: Live Crawling with Redirect History
|
|
248
|
+
Fetch a URL and inspect its headers, status, and redirect hops.
|
|
249
|
+
|
|
250
|
+
```python
|
|
251
|
+
from crawl import Crawl, CrawlError
|
|
252
|
+
|
|
253
|
+
crawler = Crawl(timeout=5.0, verify_ssl=True)
|
|
254
|
+
|
|
255
|
+
try:
|
|
256
|
+
# URL redirects http -> https
|
|
257
|
+
page = crawler.fetch("http://github.com")
|
|
258
|
+
|
|
259
|
+
print("Final Landing URL:", page.url)
|
|
260
|
+
print("Response Status Code:", page.response.status_code)
|
|
261
|
+
print("Server Header:", page.response.headers.get("server"))
|
|
262
|
+
|
|
263
|
+
# Inspect redirect history
|
|
264
|
+
if page.response.redirect_history:
|
|
265
|
+
print("\nRedirect Chain:")
|
|
266
|
+
for idx, hop in enumerate(page.response.redirect_history):
|
|
267
|
+
print(f" Hop {idx + 1}: Code {hop['status']} -> {hop['url']}")
|
|
268
|
+
|
|
269
|
+
except CrawlError as e:
|
|
270
|
+
print("Crawling failed:", e)
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
|
|
275
|
+
### Recipe 3: Extracting Tables & Forms
|
|
276
|
+
Extract structured metadata from tables and interactive form fields.
|
|
277
|
+
|
|
278
|
+
```python
|
|
279
|
+
from crawl.parser import parse_html
|
|
280
|
+
from crawl.extractor import extract_tables, extract_forms
|
|
281
|
+
|
|
282
|
+
html_content = """
|
|
283
|
+
<div>
|
|
284
|
+
<table>
|
|
285
|
+
<tr><th>Processor</th><th>Cores</th></tr>
|
|
286
|
+
<tr><td>Ryzen 9</td><td>16</td></tr>
|
|
287
|
+
<tr><td>Core i9</td><td>24</td></tr>
|
|
288
|
+
</table>
|
|
289
|
+
|
|
290
|
+
<form action="/login" method="POST">
|
|
291
|
+
<input type="text" name="username" value="user1">
|
|
292
|
+
<input type="password" name="password">
|
|
293
|
+
<button type="submit">Log In</button>
|
|
294
|
+
</form>
|
|
295
|
+
</div>
|
|
296
|
+
"""
|
|
297
|
+
|
|
298
|
+
root = parse_html(html_content)
|
|
299
|
+
|
|
300
|
+
# Extract Tables
|
|
301
|
+
tables = extract_tables(root)
|
|
302
|
+
print("Parsed Table Core List:")
|
|
303
|
+
for table in tables:
|
|
304
|
+
for row in table:
|
|
305
|
+
print(f" - {row[0]} has {row[1]} cores")
|
|
306
|
+
|
|
307
|
+
# Extract Forms
|
|
308
|
+
forms = extract_forms(root, base_url="https://mysite.com")
|
|
309
|
+
for form in forms:
|
|
310
|
+
print(f"\nForm URL: {form['action']} | Method: {form['method']}")
|
|
311
|
+
for field in form["inputs"]:
|
|
312
|
+
print(f" Field: tag={field['tag']}, name={field['name']}, default={field.get('value')}")
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
---
|
|
316
|
+
|
|
317
|
+
### Recipe 4: Decoupled Parsing, Cleaning, & Exporting
|
|
318
|
+
Decouple parsing from cleaning and output the results to JSON, CSV, or TXT.
|
|
319
|
+
|
|
320
|
+
```python
|
|
321
|
+
import os
|
|
322
|
+
from crawl.parser import parse_html
|
|
323
|
+
from crawl.cleaner import clean_dom
|
|
324
|
+
from crawl.extractor import extract_links
|
|
325
|
+
from crawl.exporter import export_json, export_csv, export_txt
|
|
326
|
+
|
|
327
|
+
html_content = """
|
|
328
|
+
<html>
|
|
329
|
+
<body>
|
|
330
|
+
<h1> Clean Me & Export </h1>
|
|
331
|
+
<p> Some paragraph </p>
|
|
332
|
+
<a href="/doc1">Doc 1</a>
|
|
333
|
+
<a href="/doc2">Doc 2</a>
|
|
334
|
+
<div class="empty-garbage"></div> <!-- gets pruned -->
|
|
335
|
+
</body>
|
|
336
|
+
</html>
|
|
337
|
+
"""
|
|
338
|
+
|
|
339
|
+
# 1. Parse DOM
|
|
340
|
+
root = parse_html(html_content)
|
|
341
|
+
|
|
342
|
+
# 2. Clean tree (normalizes text whitespace and entity unescaping)
|
|
343
|
+
clean_dom(root)
|
|
344
|
+
|
|
345
|
+
# 3. Extract Links
|
|
346
|
+
links = extract_links(root, base_url="https://site.com")
|
|
347
|
+
|
|
348
|
+
# 4. Export
|
|
349
|
+
os.makedirs("./exports", exist_ok=True)
|
|
350
|
+
export_json(links, "./exports/links.json")
|
|
351
|
+
export_csv(links, "./exports/links.csv")
|
|
352
|
+
export_txt(root.get_text(), "./exports/page_text.txt")
|
|
353
|
+
|
|
354
|
+
print("Files saved in './exports/' successfully!")
|
|
355
|
+
```
|