code / legex /scrapers /li.py
anonymous
[code] Initial release of the code.
6f5156a
"""Liechtenstein Oberster Gerichtshof (OGH) via gerichtsentscheidungen.li.
Endpoints discovered via the worldwidelaw/legal-sources project (AGPL-3.0).
We reimplement the scraping based on the public AJAX endpoints.
Flow:
1. POST /methods.aspx/getAkten {"s": "OGH.<year>"} → list of (case_number, listing_url).
2. GET <listing_url> → results page with onclick="…default.aspx?z=…" per record.
3. GET <detail_url> → metadata divs (hEIItem, aktenzeichen) and the decision text (`<div class='eintrag'>`).
The OGH hears both civil and criminal appeals; the source has no civil/criminal
flag, so `civil_filter()` is a text heuristic (presence of civil-law markers
like ABGB / ZPO and absence of criminal markers like StGB / StPO).
"""
import html
import logging
import re
import time
from datetime import date
from typing import Any
import requests
from legex.models.base import Case
from legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
BASE_URL = "https://www.gerichtsentscheidungen.li"
AKTEN_URL = f"{BASE_URL}/methods.aspx/getAkten"
USER_AGENT = "legex-research (open-data, friendly)"
REQUEST_DELAY_SECONDS = 1.0
_ONCLICK_RE = re.compile(r"onclick=\"window\.location='(default\.aspx\?z=[^']+)'\"")
_HEI_RE = re.compile(r"<div class='fL hEIItem'>([^<]+)</div>")
_AKTEN_RE = re.compile(
r"<div[^>]*class=['\"][^'\"]*aktenzeichen[^'\"]*['\"][^>]*>\s*([^<]+?)\s*</div>",
re.IGNORECASE,
)
_EINTRAG_RE = re.compile(
r"<div class=['\"]eintrag['\"][^>]*>(.*?)</div>\s*</td>",
re.DOTALL,
)
_TAG_RE = re.compile(r"<[^>]+>")
_XML_DECL_RE = re.compile(r"<\?xml[^>]*\?>")
_WS_RE = re.compile(r"[ \t]+")
_BLANK_LINES_RE = re.compile(r"\n{3,}")
_DATE_RE = re.compile(r"^(\d{1,2})\.(\d{1,2})\.(\d{4})$")
CIVIL_MARKERS = ("ABGB", "ZPO", "Zivilrechtssache", "Klagsführer", "Beklagte")
CRIMINAL_MARKERS = ("StGB", "StPO", "Angeklagte", "Strafsache")
def _parse_date(text: str) -> date | None:
m = _DATE_RE.match((text or "").strip())
if not m:
return None
try:
return date(int(m.group(3)), int(m.group(2)), int(m.group(1)))
except ValueError:
return None
def _clean_text(raw_html: str) -> str:
text = _XML_DECL_RE.sub("", raw_html)
text = _TAG_RE.sub(" ", text)
text = html.unescape(text)
text = _WS_RE.sub(" ", text)
text = re.sub(r" ?\n ?", "\n", text)
text = _BLANK_LINES_RE.sub("\n\n", text)
return text.strip()
class LIScraper(BaseScraper):
country = "Liechtenstein"
def scrape(
self,
start_date: date | None = None,
end_date: date | None = None,
) -> list[Case]:
start = start_date or date(2015, 1, 1)
end = end_date or date(2025, 12, 31)
session = requests.Session()
session.headers.update({"User-Agent": USER_AGENT})
cases: list[Case] = []
seen: set[str] = set()
for year in range(start.year, end.year + 1):
rows = self._get_akten(session, f"OGH.{year}")
log.info("LI OGH.%d: %d rows", year, len(rows))
for row in rows:
if not isinstance(row, list) or len(row) < 2:
continue
case_number = (row[0] or "").strip()
listing_path = (row[1] or "").strip()
if not case_number or not listing_path or case_number in seen:
continue
detail_path = self._find_detail_path(session, listing_path)
if not detail_path:
continue
case = self._fetch_detail(session, case_number, detail_path)
if case is None:
continue
if start_date and case.decision_date and case.decision_date < start_date:
continue
if end_date and case.decision_date and case.decision_date > end_date:
continue
seen.add(case_number)
cases.append(case)
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
log.info("Collected %d Liechtenstein OGH cases", len(cases))
return cases
@staticmethod
def _get_akten(session: requests.Session, prefix: str) -> list[Any]:
try:
resp = session.post(
AKTEN_URL,
json={"s": prefix},
headers={"Content-Type": "application/json; charset=utf-8"},
timeout=60,
)
resp.raise_for_status()
data = resp.json()
except Exception as e:
log.warning("LI getAkten(%s) failed (%s)", prefix, e)
return []
time.sleep(REQUEST_DELAY_SECONDS)
return data.get("d", []) or []
@staticmethod
def _find_detail_path(session: requests.Session, listing_path: str) -> str | None:
url = f"{BASE_URL}/{listing_path.lstrip('/')}"
try:
resp = session.get(url, timeout=60)
resp.raise_for_status()
except Exception as e:
log.warning("LI listing fetch failed %s (%s)", listing_path, e)
return None
time.sleep(REQUEST_DELAY_SECONDS)
for m in _ONCLICK_RE.finditer(resp.text):
target = m.group(1)
if "z=" in target and len(target) > 30:
return target
return None
def _fetch_detail(
self,
session: requests.Session,
case_number: str,
detail_path: str,
) -> Case | None:
url = f"{BASE_URL}/{detail_path.lstrip('/')}"
try:
resp = session.get(url, timeout=60)
resp.raise_for_status()
except Exception as e:
log.warning("LI detail fetch failed %s (%s)", case_number, e)
return None
time.sleep(REQUEST_DELAY_SECONDS)
page = resp.text
items = _HEI_RE.findall(page)
decision_date: date | None = None
decision_type: str | None = None
court: str | None = None
for item in items:
item = item.strip()
if decision_date is None:
d = _parse_date(item)
if d is not None:
decision_date = d
continue
if item in ("OGH", "StGH", "OG", "LG", "VGH"):
court = item
continue
if item in ("Urteil", "Beschluss", "Entscheidung", "Gutachten"):
decision_type = item
# Use the OGH decision number as the unique case_id. The underlying LG
# `aktenzeichen` (e.g. "09 CG. 2011.232") is the case file at first
# instance — it can repeat when one underlying case spawns multiple OGH
# decisions (different appellants, split rulings) on the same day.
akten_match = _AKTEN_RE.search(page)
aktenzeichen = akten_match.group(1).strip() if akten_match else ""
text_match = _EINTRAG_RE.search(page)
full_text = _clean_text(text_match.group(1)) if text_match else None
return Case(
case_id=case_number,
link=url,
decision_date=decision_date,
jurisdiction="li",
language="de",
full_text=full_text or None,
metadata={
"court": court or "OGH",
"decision_type": decision_type or "",
"aktenzeichen": aktenzeichen,
},
)
@staticmethod
def civil_filter(cases: list[Case]) -> list[Case]:
kept: list[Case] = []
for c in cases:
text = c.full_text or ""
if not text:
continue
if any(marker in text for marker in CRIMINAL_MARKERS):
continue
if not any(marker in text for marker in CIVIL_MARKERS):
continue
kept.append(c)
log.info("LI civil_filter kept %d/%d", len(kept), len(cases))
return kept