code / legex /scrapers /rs.py
anonymous
[code] Initial release of the code.
6f5156a
"""Serbian Supreme Court (Vrhovni sud) via the public Solr search listing.
The court runs Drupal 7 with a Solr backend at `vrh.sud.rs`. The
`/sr-lat/solr-search-page/results` endpoint sorts by date (newest first) and
exposes each case's reference (e.g., "Rev 102/2025"), detail URL, and
decision date in the result-summary block — enough for a Goldenset without
fetching detail pages.
Civil filter: case-ID prefix `Rev/Rev1/Rev2/Prev/Gzz/Gzz1` (civil revision).
Drop `Kzz`, `Kž` (criminal). Server-side `Građanska materija` (civil matter)
marker is also captured into metadata.
"""
import logging
import re
import time
from datetime import date
import requests
import urllib3
from legex.models.base import Case
from legex.scrapers.base import BaseScraper
# vrh.sud.rs serves a Let's Encrypt cert without the intermediate in the chain
# (AIA-only), so `requests` can't verify it out of the box. Disable verification
# for this read-only scrape of public open-data; we don't transmit secrets.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
log = logging.getLogger(__name__)
BASE_URL = "https://vrh.sud.rs"
SEARCH_PATH = "/sr-lat/solr-search-page/results"
USER_AGENT = "legex-research (open-data, friendly)"
RESULTS_PER_PAGE = 50
MAX_PAGES = 400
DELAY_SECONDS = 0.5
_RESULT_BLOCK_RE = re.compile(
r'<li class="search-result">(.*?)</li>', re.DOTALL
)
_LINK_RE = re.compile(
r'<h3[^>]*class="title[^"]*"[^>]*>\s*<a href="([^"]+)"[^>]*>(.*?)</a>',
re.DOTALL,
)
_SUMMARY_RE = re.compile(
r'<div class="result-summary">(.*?)</div>', re.DOTALL
)
_DATE_RE = re.compile(r"Datum:\s*(\d{2})\.(\d{2})\.(\d{4})")
_PREFIX_RE = re.compile(r"^([A-Za-zžŽ]+\d*)\s")
CIVIL_PREFIXES = {"rev", "rev1", "rev2", "prev", "gzz", "gzz1"}
CRIMINAL_PREFIXES = {"kzz", "kž", "kz"}
def _normalize_text(raw: str) -> str:
return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", raw)).strip()
def _parse_block(block_html: str) -> dict | None:
link_match = _LINK_RE.search(block_html)
if not link_match:
return None
href = link_match.group(1).strip()
case_ref = _normalize_text(link_match.group(2))
# Strip optional category code suffix like "3.2.1.3.1" from end of title.
case_id = re.sub(r"\s+\d+(\.\d+)+$", "", case_ref).strip()
summary_match = _SUMMARY_RE.search(block_html)
summary_text = _normalize_text(summary_match.group(1)) if summary_match else ""
decision_date: date | None = None
d = _DATE_RE.search(summary_text)
if d:
try:
decision_date = date(int(d.group(3)), int(d.group(2)), int(d.group(1)))
except ValueError:
decision_date = None
matter = "other"
if "Građanska" in summary_text or "Gradjanska" in summary_text:
matter = "civil"
elif "Krivična" in summary_text or "Krivicna" in summary_text:
matter = "criminal"
elif "Upravna" in summary_text:
matter = "administrative"
prefix_match = _PREFIX_RE.search(case_id)
prefix = prefix_match.group(1).lower() if prefix_match else ""
return {
"case_id": case_id,
"link": href if href.startswith("http") else f"{BASE_URL}{href}",
"decision_date": decision_date,
"matter": matter,
"case_prefix": prefix,
"summary": summary_text,
}
class RSScraper(BaseScraper):
country = "Serbien"
def scrape(
self,
start_date: date | None = None,
end_date: date | None = None,
) -> list[Case]:
session = requests.Session()
session.headers.update({"User-Agent": USER_AGENT})
cases: list[Case] = []
seen: set[str] = set()
for page in range(0, MAX_PAGES):
url = (
f"{BASE_URL}{SEARCH_PATH}"
f"?court_type=sc&results={RESULTS_PER_PAGE}"
f"&page={page}&sorting=by_date_down"
)
try:
resp = session.get(url, timeout=30, verify=False)
except requests.RequestException as e:
log.warning("RS request error page %d: %s", page, e)
break
if resp.status_code != 200:
log.warning("RS HTTP %d on page %d", resp.status_code, page)
break
blocks = _RESULT_BLOCK_RE.findall(resp.text)
if not blocks:
log.info("RS page %d: no results, stopping", page)
break
new_on_page = 0
oldest_on_page: date | None = None
for block in blocks:
parsed = _parse_block(block)
if not parsed:
continue
if parsed["case_id"] in seen:
continue
if (
start_date
and parsed["decision_date"]
and parsed["decision_date"] < start_date
):
if not oldest_on_page or parsed["decision_date"] < oldest_on_page:
oldest_on_page = parsed["decision_date"]
continue
if (
end_date
and parsed["decision_date"]
and parsed["decision_date"] > end_date
):
continue
seen.add(parsed["case_id"])
new_on_page += 1
if not oldest_on_page or (
parsed["decision_date"]
and parsed["decision_date"] < oldest_on_page
):
oldest_on_page = parsed["decision_date"]
cases.append(
Case(
case_id=parsed["case_id"],
link=parsed["link"],
decision_date=parsed["decision_date"],
jurisdiction="rs",
language="sr",
full_text=None,
metadata={
"matter": parsed["matter"],
"case_prefix": parsed["case_prefix"],
"summary": parsed["summary"],
},
)
)
log.info(
"RS page %d: %d blocks, %d new (oldest seen %s)",
page,
len(blocks),
new_on_page,
oldest_on_page,
)
# Sorted desc by date: once we fully cross start_date, no more in range.
if (
start_date
and oldest_on_page
and oldest_on_page < start_date
and new_on_page == 0
):
log.info("RS page %d entirely older than start_date; stopping", page)
break
time.sleep(DELAY_SECONDS)
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
log.info("Collected %d Serbia cases", len(cases))
return cases
@staticmethod
def civil_filter(cases: list[Case]) -> list[Case]:
kept: list[Case] = []
for c in cases:
meta = c.metadata or {}
prefix = (meta.get("case_prefix") or "").lower()
matter = meta.get("matter")
if prefix in CRIMINAL_PREFIXES:
continue
if matter == "criminal":
continue
if prefix in CIVIL_PREFIXES or matter == "civil":
kept.append(c)
log.info("RS civil_filter kept %d/%d", len(kept), len(cases))
return kept