urban-json-html 0.1.0__py3-none-any.whl
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.
- urban_json_html/__init__.py +166 -0
- urban_json_html/py.typed +0 -0
- urban_json_html-0.1.0.dist-info/METADATA +49 -0
- urban_json_html-0.1.0.dist-info/RECORD +8 -0
- urban_json_html-0.1.0.dist-info/WHEEL +5 -0
- urban_json_html-0.1.0.dist-info/entry_points.txt +2 -0
- urban_json_html-0.1.0.dist-info/licenses/LICENSE +21 -0
- urban_json_html-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Plugin urban-json : conversion HTML vers JSON (``loadhtml``).
|
|
2
|
+
|
|
3
|
+
Port de ``ServiceHtml`` / ``HtmlToJson`` (.NET, HtmlAgilityPack) avec le
|
|
4
|
+
``html.parser`` de la bibliothèque standard, sans dépendance. Forme produite,
|
|
5
|
+
identique au .NET :
|
|
6
|
+
|
|
7
|
+
* élément -> ``{"#id": balise, <attributs>…, "content": enfant | [enfants]}``
|
|
8
|
+
(``content`` absent sans enfant, valeur seule pour un enfant unique) ;
|
|
9
|
+
* texte -> ``"#text: <texte brut>"``, ignoré s'il n'est fait que de blancs ;
|
|
10
|
+
* commentaire et ``<!DOCTYPE>`` -> ``"#comment: <!-- … -->"`` (HtmlAgilityPack
|
|
11
|
+
range la déclaration DOCTYPE parmi les commentaires) ;
|
|
12
|
+
* racine -> ``{"#id": "#document", …}``.
|
|
13
|
+
|
|
14
|
+
Comme HtmlAgilityPack, le texte garde ses entités telles quelles (``&``) et
|
|
15
|
+
la casse d'origine des balises est conservée. Écarts : les noms d'attributs sont
|
|
16
|
+
mis en minuscules et leurs valeurs décodées (``html.parser`` le fait toujours) ;
|
|
17
|
+
un chemin relatif est accepté (le .NET exigeait un chemin absolu ou une URI).
|
|
18
|
+
|
|
19
|
+
Découvert automatiquement via l'entry point ``urban_json.functions``.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
import re
|
|
26
|
+
from html.parser import HTMLParser
|
|
27
|
+
from typing import Any
|
|
28
|
+
from urllib.parse import unquote, urlparse
|
|
29
|
+
|
|
30
|
+
from urban_json import JsltError
|
|
31
|
+
|
|
32
|
+
__version__ = "0.1.0"
|
|
33
|
+
|
|
34
|
+
__all__ = ["execute_loadhtml", "html_to_json", "register"]
|
|
35
|
+
|
|
36
|
+
#: Délai maximal (secondes) pour charger une page distante.
|
|
37
|
+
DEFAULT_TIMEOUT = 30.0
|
|
38
|
+
|
|
39
|
+
# Éléments HTML sans contenu ni balise fermante.
|
|
40
|
+
_VOID = {
|
|
41
|
+
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta",
|
|
42
|
+
"param", "source", "track", "wbr",
|
|
43
|
+
}
|
|
44
|
+
_TAG_NAME = re.compile(r"<\s*([^\s/>]+)")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class _Node:
|
|
48
|
+
__slots__ = ("attrs", "children", "name")
|
|
49
|
+
|
|
50
|
+
def __init__(self, name: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
51
|
+
self.name = name
|
|
52
|
+
self.attrs = attrs
|
|
53
|
+
self.children: list[Any] = []
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class _TreeBuilder(HTMLParser):
|
|
57
|
+
def __init__(self) -> None:
|
|
58
|
+
super().__init__(convert_charrefs=False)
|
|
59
|
+
self.root = _Node("#document", [])
|
|
60
|
+
self.stack = [self.root]
|
|
61
|
+
|
|
62
|
+
def _append(self, item: Any) -> None:
|
|
63
|
+
self.stack[-1].children.append(item)
|
|
64
|
+
|
|
65
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
66
|
+
raw = self.get_starttag_text() or ""
|
|
67
|
+
match = _TAG_NAME.match(raw)
|
|
68
|
+
node = _Node(match.group(1) if match else tag, attrs)
|
|
69
|
+
self._append(node)
|
|
70
|
+
if tag not in _VOID:
|
|
71
|
+
self.stack.append(node)
|
|
72
|
+
|
|
73
|
+
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
74
|
+
raw = self.get_starttag_text() or ""
|
|
75
|
+
match = _TAG_NAME.match(raw)
|
|
76
|
+
self._append(_Node(match.group(1) if match else tag, attrs))
|
|
77
|
+
|
|
78
|
+
def handle_endtag(self, tag: str) -> None:
|
|
79
|
+
# Ferme jusqu'à la balise ouverte correspondante ; une fermante orpheline est ignorée.
|
|
80
|
+
for depth in range(len(self.stack) - 1, 0, -1):
|
|
81
|
+
if self.stack[depth].name.lower() == tag:
|
|
82
|
+
del self.stack[depth:]
|
|
83
|
+
return
|
|
84
|
+
|
|
85
|
+
def handle_data(self, data: str) -> None:
|
|
86
|
+
self._append(("#text", data))
|
|
87
|
+
|
|
88
|
+
def handle_entityref(self, name: str) -> None:
|
|
89
|
+
self._append(("#text", f"&{name};"))
|
|
90
|
+
|
|
91
|
+
def handle_charref(self, name: str) -> None:
|
|
92
|
+
self._append(("#text", f"&#{name};"))
|
|
93
|
+
|
|
94
|
+
def handle_comment(self, data: str) -> None:
|
|
95
|
+
self._append(("#comment", f"<!--{data}-->"))
|
|
96
|
+
|
|
97
|
+
def handle_decl(self, decl: str) -> None:
|
|
98
|
+
self._append(("#comment", f"<!{decl}>"))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _merge_text(children: list[Any]) -> list[Any]:
|
|
102
|
+
"""Recolle les morceaux de texte consécutifs (le parseur coupe sur les entités)."""
|
|
103
|
+
merged: list[Any] = []
|
|
104
|
+
for child in children:
|
|
105
|
+
if isinstance(child, tuple) and child[0] == "#text" and merged and isinstance(merged[-1], tuple) \
|
|
106
|
+
and merged[-1][0] == "#text":
|
|
107
|
+
merged[-1] = ("#text", merged[-1][1] + child[1])
|
|
108
|
+
else:
|
|
109
|
+
merged.append(child)
|
|
110
|
+
return merged
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _to_json(item: Any) -> Any:
|
|
114
|
+
if isinstance(item, tuple):
|
|
115
|
+
kind, text = item
|
|
116
|
+
return f"{kind}: {text}" if text.strip() else None
|
|
117
|
+
result: dict[str, Any] = {"#id": item.name}
|
|
118
|
+
for name, value in item.attrs:
|
|
119
|
+
result.setdefault(name, value if value is not None else "")
|
|
120
|
+
children = [c for c in (_to_json(child) for child in _merge_text(item.children)) if c is not None]
|
|
121
|
+
if len(children) == 1:
|
|
122
|
+
result["content"] = children[0]
|
|
123
|
+
elif children:
|
|
124
|
+
result["content"] = children
|
|
125
|
+
return result
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def html_to_json(payload: str) -> dict:
|
|
129
|
+
"""Convertit un texte HTML en JSON (forme ``HtmlToJson`` du .NET)."""
|
|
130
|
+
builder = _TreeBuilder()
|
|
131
|
+
builder.feed(payload)
|
|
132
|
+
builder.close()
|
|
133
|
+
return _to_json(builder.root)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _fetch_url(url: str) -> str:
|
|
137
|
+
"""Charge une page distante. Point d'injection pour les tests."""
|
|
138
|
+
from urllib.request import Request, urlopen
|
|
139
|
+
|
|
140
|
+
request = Request(url, headers={"User-Agent": "urban-json-html"})
|
|
141
|
+
with urlopen(request, timeout=DEFAULT_TIMEOUT) as response:
|
|
142
|
+
charset = response.headers.get_content_charset() or "utf-8"
|
|
143
|
+
return response.read().decode(charset, errors="replace")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def execute_loadhtml(ctx: Any, path: Any = None) -> dict:
|
|
147
|
+
if not path:
|
|
148
|
+
raise JsltError("loadhtml : le chemin ou l'URL de la page est requis")
|
|
149
|
+
location = str(path)
|
|
150
|
+
parsed = urlparse(location)
|
|
151
|
+
if parsed.scheme in ("http", "https"):
|
|
152
|
+
return html_to_json(_fetch_url(location))
|
|
153
|
+
file_path = unquote(parsed.path) if parsed.scheme == "file" else location
|
|
154
|
+
if not os.path.isfile(file_path):
|
|
155
|
+
raise JsltError(f"loadhtml : page HTML introuvable {file_path!r}")
|
|
156
|
+
with open(file_path, encoding="utf-8-sig", errors="replace") as handle:
|
|
157
|
+
return html_to_json(handle.read())
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def register(registry: Any) -> None:
|
|
161
|
+
"""Enregistre ``loadhtml``."""
|
|
162
|
+
registry.register(
|
|
163
|
+
"loadhtml",
|
|
164
|
+
execute_loadhtml,
|
|
165
|
+
description="Charge une page HTML (fichier ou URL http/https) et la convertit en JSON {#id, attributs, content}",
|
|
166
|
+
)
|
urban_json_html/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: urban-json-html
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Plugin urban-json : conversion HTML vers JSON (loadhtml).
|
|
5
|
+
Author-email: Gael Beard <gaelgael5@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/gaelgael5/Jslt
|
|
8
|
+
Project-URL: Repository, https://github.com/gaelgael5/Jslt
|
|
9
|
+
Keywords: json,transform,template,jslt,html,plugin
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Topic :: Text Processing :: Markup
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: urban-json
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# urban-json-html
|
|
29
|
+
|
|
30
|
+
Plugin [urban-json](https://github.com/gaelgael5/Jslt) : **HTML vers JSON** dans les
|
|
31
|
+
templates, via `loadhtml(chemin_ou_url)` (port de `ServiceHtml`, .NET). Aucune
|
|
32
|
+
dépendance : `html.parser` de la bibliothèque standard.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install urban-json-html
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Forme produite (celle du .NET, HtmlAgilityPack) :
|
|
39
|
+
|
|
40
|
+
```json
|
|
41
|
+
{ "#id": "#document", "content": { "#id": "p", "class": "x", "content": "#text: Bonjour" } }
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
- élément → `{"#id": balise, attributs…, "content": enfant | [enfants]}` ;
|
|
45
|
+
- texte → `"#text: …"` (blancs seuls ignorés, entités conservées) ;
|
|
46
|
+
- commentaire et `<!DOCTYPE>` → `"#comment: …"`.
|
|
47
|
+
|
|
48
|
+
`loadhtml` accepte un fichier (chemin ou URI `file://`) ou une URL `http(s)://`
|
|
49
|
+
(délai de 30 s). Attention aux URL issues de données non fiables (SSRF).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
urban_json_html/__init__.py,sha256=h852DrxLxFgXTfOe9pQs33FvPiydiAE-o7_70roXygw,6067
|
|
2
|
+
urban_json_html/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
urban_json_html-0.1.0.dist-info/licenses/LICENSE,sha256=LdXMQzg0w6hrGI_vhgHsmOLKcHTkyF5PyUXkP9fV7mA,1068
|
|
4
|
+
urban_json_html-0.1.0.dist-info/METADATA,sha256=fcaOTEGXp3QQdAK2DAcuoZZPeA4-TjIJ33RMlCRiIK8,1895
|
|
5
|
+
urban_json_html-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
urban_json_html-0.1.0.dist-info/entry_points.txt,sha256=kfvs9-zAVUnPvaTugeaugRlEvYvu0TIS_l9npgkEDLo,55
|
|
7
|
+
urban_json_html-0.1.0.dist-info/top_level.txt,sha256=eQgfMqtQtQnDLz6zKVK9JZVEZ0uS6jrJd4a8ytJ-lCk,16
|
|
8
|
+
urban_json_html-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 black beard
|
|
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 @@
|
|
|
1
|
+
urban_json_html
|