listract 0.1.0__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.
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: listract
3
+ Version: 0.1.0
4
+ Summary: Cross-language structural list extraction with a shared JSON model
5
+ Author: isesword
6
+ License: MIT
7
+ Project-URL: Homepage, https://isesword.github.io/Listract/
8
+ Project-URL: Repository, https://github.com/isesword/Listract
9
+ Project-URL: Documentation, https://github.com/isesword/Listract#readme
10
+ Project-URL: Issues, https://github.com/isesword/Listract/issues
11
+ Keywords: list extraction,html,scraping,dom,structural analysis
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Topic :: Text Processing :: Markup :: HTML
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ Requires-Dist: lxml>=6.1
26
+ Requires-Dist: requests>=2.32
27
+ Provides-Extra: browser
28
+ Requires-Dist: playwright>=1.65; extra == "browser"
29
+
30
+ # Listract
31
+
32
+ **Listract = List + Extract.** Structural list extraction from raw HTML: decide whether the page is a list, identify the main list container, and return cleaned entries as one shared JSON model.
33
+
34
+ The Python package bundles the extraction model. No separate model download is required.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install listract
40
+ ```
41
+
42
+ Requires Python 3.9 or newer.
43
+
44
+ ## Quickstart
45
+
46
+ ```python
47
+ from listract import ListExtractor
48
+
49
+ extractor = ListExtractor()
50
+ result = extractor.extract_html(html)
51
+
52
+ print(result["status"]) # list / no_list
53
+ print(result["action"]) # e.g. fast_list
54
+ print(result["entries"]) # cleaned list entries
55
+ ```
56
+
57
+ `ListExtractor()` loads the bundled model from inside the wheel. Set `LIST_EXTRACT_MODEL_DIR` only when overriding it with a custom model.
58
+
59
+ ## What it returns
60
+
61
+ Listract returns a shared JSON contract covering:
62
+
63
+ - page-level `status` (`list` / `no_list`)
64
+ - production `action`
65
+ - the selected list container
66
+ - cleaned entries and their links
67
+ - manifest and verification helpers
68
+
69
+ ## Links
70
+
71
+ - Repository: https://github.com/isesword/Listract
72
+ - Documentation: https://isesword.github.io/Listract/
73
+ - Chinese README: https://github.com/isesword/Listract/blob/main/README.zh-CN.md
74
+ - Issues: https://github.com/isesword/Listract/issues
75
+
76
+ ## License
77
+
78
+ MIT
@@ -0,0 +1,49 @@
1
+ # Listract
2
+
3
+ **Listract = List + Extract.** Structural list extraction from raw HTML: decide whether the page is a list, identify the main list container, and return cleaned entries as one shared JSON model.
4
+
5
+ The Python package bundles the extraction model. No separate model download is required.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install listract
11
+ ```
12
+
13
+ Requires Python 3.9 or newer.
14
+
15
+ ## Quickstart
16
+
17
+ ```python
18
+ from listract import ListExtractor
19
+
20
+ extractor = ListExtractor()
21
+ result = extractor.extract_html(html)
22
+
23
+ print(result["status"]) # list / no_list
24
+ print(result["action"]) # e.g. fast_list
25
+ print(result["entries"]) # cleaned list entries
26
+ ```
27
+
28
+ `ListExtractor()` loads the bundled model from inside the wheel. Set `LIST_EXTRACT_MODEL_DIR` only when overriding it with a custom model.
29
+
30
+ ## What it returns
31
+
32
+ Listract returns a shared JSON contract covering:
33
+
34
+ - page-level `status` (`list` / `no_list`)
35
+ - production `action`
36
+ - the selected list container
37
+ - cleaned entries and their links
38
+ - manifest and verification helpers
39
+
40
+ ## Links
41
+
42
+ - Repository: https://github.com/isesword/Listract
43
+ - Documentation: https://isesword.github.io/Listract/
44
+ - Chinese README: https://github.com/isesword/Listract/blob/main/README.zh-CN.md
45
+ - Issues: https://github.com/isesword/Listract/issues
46
+
47
+ ## License
48
+
49
+ MIT
@@ -0,0 +1,16 @@
1
+ """Template-free structural list extraction.
2
+
3
+ The package is intentionally small and dependency-light:
4
+ - DOM parsing: lxml
5
+ - static fetch: requests
6
+ - browser fallback: playwright (optional at runtime)
7
+ """
8
+
9
+ from .extractor import ListExtractor
10
+ from .features import analyze_html
11
+ from .manifest import build_manifest, diff_manifest, verify_click_entries, verify_link
12
+ from .production_gate import input_health, production_decision
13
+
14
+ __version__ = "0.1.0"
15
+
16
+ __all__ = ["ListExtractor", "analyze_html", "build_manifest", "diff_manifest", "verify_link", "verify_click_entries", "production_decision", "input_health"]
@@ -0,0 +1,286 @@
1
+ """Generic click-only list resolver.
2
+
3
+ Some list rows are ``div``/``li`` elements with no ``<a href>``: the detail URL
4
+ only exists after the row's click handler runs (``window.open``, Vue router,
5
+ ``location.href``, ...). This module discovers such repeated rows structurally
6
+ and resolves the final URL with a trusted Playwright click.
7
+
8
+ There are no school names, domains or fixed selectors here.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import time
14
+ from typing import Any
15
+ from urllib.parse import urlparse
16
+
17
+ from lxml import html as LH
18
+
19
+ from .features import (
20
+ DATE_RE,
21
+ SCORE_RE,
22
+ _boilerplate_score,
23
+ canonicalize_url,
24
+ clean_title,
25
+ norm_text,
26
+ textlen,
27
+ )
28
+
29
+ SKIP_TAGS = {
30
+ "head", "html", "body", "script", "style", "noscript",
31
+ "nav", "header", "footer", "aside",
32
+ }
33
+
34
+
35
+ def _clean_tree(raw: str) -> Any:
36
+ d = LH.fromstring(raw)
37
+ for bad in d.xpath("//script|//style|//noscript"):
38
+ parent = bad.getparent()
39
+ if parent is not None:
40
+ parent.remove(bad)
41
+ return d
42
+
43
+
44
+ def _text_len(s: str) -> int:
45
+ return len(re.sub(r"\s+", "", s or ""))
46
+
47
+
48
+ def find_clickable_lists(raw: str, max_results: int = 5) -> list[dict[str, Any]]:
49
+ """Return repeated href-less row groups, ordered by structural score.
50
+
51
+ A row group is a set of sibling children sharing a class signature. It is
52
+ click-only when almost none of the rows contain an ``<a href>`` and the
53
+ rows carry title/date-sized text.
54
+ """
55
+ d = _clean_tree(raw)
56
+ page_text = norm_text(d.text_content())
57
+ page_len = max(1, textlen(page_text))
58
+ out: list[dict[str, Any]] = []
59
+ for el in d.iter():
60
+ if not isinstance(el.tag, str) or el.tag in SKIP_TAGS:
61
+ continue
62
+ kids = [c for c in el if isinstance(c.tag, str)]
63
+ if len(kids) < 3:
64
+ continue
65
+ groups: dict[tuple[str, tuple[str, ...]], list[Any]] = {}
66
+ for child in kids:
67
+ key = (child.tag, tuple(sorted((child.get("class") or "").split())))
68
+ groups.setdefault(key, []).append(child)
69
+ specs: list[tuple[Any, list[Any], bool]] = [
70
+ (key, group, False) for key, group in groups.items() if len(group) >= 3
71
+ ]
72
+ # Loose fallback only when exact classes are too fragmented. If one
73
+ # exact group already covers most children, mixing breadcrumbs or
74
+ # "view more" rows into it would corrupt the row count.
75
+ largest_exact = max((len(g) for g in groups.values()), default=0)
76
+ if largest_exact < 3:
77
+ by_tag: dict[str, list[Any]] = {}
78
+ for child in kids:
79
+ by_tag.setdefault(child.tag, []).append(child)
80
+ for tag, group in by_tag.items():
81
+ if len(group) >= 3:
82
+ specs.append((f"LOOSE|{tag}", group, True))
83
+ for key, rows, loose in specs:
84
+ hrefs = sum(len(r.xpath(".//a[@href]")) for r in rows)
85
+ if hrefs > max(1, len(rows) * 0.2):
86
+ continue
87
+ texts = [norm_text(r.text_content()) for r in rows]
88
+ lens = [_text_len(t) for t in texts]
89
+ if not lens or sum(lens) / len(lens) < 8:
90
+ continue
91
+ dates = sum(1 for t in texts if DATE_RE.search(t))
92
+ date_ratio = dates / len(rows)
93
+ titleish = sum(1 for t in texts if len(clean_title(re.sub(DATE_RE, "", t))) >= 6)
94
+ share = textlen(el.text_content()) / page_len
95
+ bl = _boilerplate_score(el)
96
+ if share > 0.85 or bl > 3:
97
+ continue
98
+ score = 4 * min(len(rows), 10) + 2 * dates + titleish
99
+ if date_ratio >= 0.4:
100
+ score += 3
101
+ score -= 2 * bl
102
+ out.append({
103
+ "container_xpath": d.getroottree().getpath(el),
104
+ "container_tag": el.tag,
105
+ "container_class": (el.get("class") or "")[:120],
106
+ "selector_path": _selector_path(el),
107
+ "n": len(rows),
108
+ "date_ratio": round(date_ratio, 3),
109
+ "avg_len": round(sum(lens) / len(lens), 1),
110
+ "share": round(share, 3),
111
+ "loose": loose,
112
+ "score": round(score, 1),
113
+ "rows": [
114
+ {
115
+ "xpath": d.getroottree().getpath(r),
116
+ "tag": r.tag,
117
+ "class": (r.get("class") or "")[:120],
118
+ "text": t[:300],
119
+ "title": clean_title(re.sub(DATE_RE, "", t)),
120
+ "date": (DATE_RE.search(t).group(0) if DATE_RE.search(t) else ""),
121
+ }
122
+ for r, t in zip(rows, texts)
123
+ ],
124
+ })
125
+ seen: set[str] = set()
126
+ final: list[dict[str, Any]] = []
127
+ for c in sorted(out, key=lambda x: x["score"], reverse=True):
128
+ if c["container_xpath"] in seen:
129
+ continue
130
+ seen.add(c["container_xpath"])
131
+ final.append(c)
132
+ return final[:max_results]
133
+
134
+
135
+ def _selector_path(el: Any) -> str:
136
+ """Compact selector used only for display/gold alignment."""
137
+ parts: list[str] = []
138
+ cur = el
139
+ while cur is not None and isinstance(cur.tag, str) and len(parts) < 4:
140
+ bit = cur.tag
141
+ if cur.get("id"):
142
+ bit += f"#{cur.get('id')}"
143
+ elif cur.get("class"):
144
+ bit += "." + ".".join((cur.get("class") or "").split()[:2])
145
+ parts.append(bit)
146
+ cur = cur.getparent()
147
+ return " > ".join(reversed(parts))
148
+
149
+
150
+ def is_relevant_click_candidate(candidate: dict[str, Any], page_text: str = "") -> bool:
151
+ """Cheap business gate before spending clicks.
152
+
153
+ A click-only group should look like an article/score list, not a homepage
154
+ news carousel or a map filter. This is a content/structural signal, not a
155
+ site rule; the downstream page-status and semantic models still decide.
156
+ """
157
+ if int(candidate.get("n") or 0) < 4:
158
+ return False
159
+ if float(candidate.get("date_ratio") or 0) < 0.5:
160
+ return False
161
+ if float(candidate.get("avg_len") or 0) < 10:
162
+ return False
163
+ group_text = " ".join(r.get("text") or "" for r in candidate.get("rows") or [])
164
+ return bool(SCORE_RE.search(group_text) or SCORE_RE.search(page_text[:3000]))
165
+
166
+
167
+ def _click_target(page: Any, row_xpath: str) -> tuple[str, str]:
168
+ """Return (url, target_kind) for one row; no fake URL is produced."""
169
+ target = page.locator("xpath=" + row_xpath)
170
+ before = page.url
171
+ popups: list[Any] = []
172
+
173
+ def on_popup(p: Any) -> None:
174
+ popups.append(p)
175
+
176
+ page.once("popup", on_popup)
177
+ try:
178
+ target.click(timeout=5000)
179
+ page.wait_for_timeout(1800)
180
+ if popups:
181
+ p = popups[0]
182
+ try:
183
+ p.wait_for_load_state("domcontentloaded", timeout=5000)
184
+ except Exception:
185
+ pass
186
+ url = p.url
187
+ try:
188
+ p.close()
189
+ except Exception:
190
+ pass
191
+ if url and url != "about:blank":
192
+ return url, "row"
193
+ if page.url != before:
194
+ return page.url, "row"
195
+ except Exception:
196
+ pass
197
+ # A handler can be on a nested title node instead of the row itself.
198
+ for xp in (
199
+ ".//span[@title or @aria-label]",
200
+ ".//span[normalize-space()]",
201
+ ".//p[normalize-space()]",
202
+ ".//a",
203
+ ".//div[normalize-space()]",
204
+ ):
205
+ try:
206
+ child = target.locator("xpath=" + xp).first
207
+ if child.count() == 0:
208
+ continue
209
+ except Exception:
210
+ continue
211
+ popups.clear()
212
+ page.once("popup", on_popup)
213
+ before2 = page.url
214
+ try:
215
+ child.click(timeout=5000)
216
+ page.wait_for_timeout(1800)
217
+ if popups:
218
+ p = popups[0]
219
+ try:
220
+ p.wait_for_load_state("domcontentloaded", timeout=5000)
221
+ except Exception:
222
+ pass
223
+ url = p.url
224
+ try:
225
+ p.close()
226
+ except Exception:
227
+ pass
228
+ if url and url != "about:blank":
229
+ return url, "child"
230
+ if page.url != before2:
231
+ return page.url, "child"
232
+ except Exception:
233
+ continue
234
+ return "", "none"
235
+
236
+
237
+ def _restore(page: Any, base_url: str) -> None:
238
+ if page.url.split("#")[0] == base_url.split("#")[0]:
239
+ return
240
+ try:
241
+ page.go_back(timeout=10000)
242
+ page.wait_for_timeout(1000)
243
+ except Exception:
244
+ try:
245
+ page.goto(base_url, wait_until="domcontentloaded", timeout=30000)
246
+ page.wait_for_timeout(1500)
247
+ except Exception:
248
+ pass
249
+
250
+
251
+ def resolve_click_candidate(
252
+ page: Any,
253
+ base_url: str,
254
+ candidate: dict[str, Any],
255
+ max_rows: int | None = None,
256
+ ) -> dict[str, dict[str, Any]]:
257
+ """Click every row in one candidate and return a row-xpath -> link map.
258
+
259
+ A row whose click produces no URL is recorded as ``linkless``; it is never
260
+ assigned an invented detail URL. The main page is restored after same-tab
261
+ navigation, and popup pages are closed immediately.
262
+ """
263
+ links: dict[str, dict[str, Any]] = {}
264
+ rows = candidate.get("rows") or []
265
+ if max_rows is not None:
266
+ rows = rows[:max_rows]
267
+ for row in rows:
268
+ _restore(page, base_url)
269
+ url, target_kind = _click_target(page, row["xpath"])
270
+ title = clean_title(row.get("title") or row.get("text") or "")
271
+ date = row.get("date") or ""
272
+ if url:
273
+ url = canonicalize_url(base_url, url)
274
+ status = "resolved"
275
+ else:
276
+ status = "linkless"
277
+ links[row["xpath"]] = {
278
+ "title": title[:200],
279
+ "date": date,
280
+ "url": url,
281
+ "link_mode": "click",
282
+ "link_status": status,
283
+ "target": target_kind,
284
+ }
285
+ _restore(page, base_url)
286
+ return links