| |
| """Discover gov.pl subsites + their news-section paths and write a committed |
| manifest (govpl_subsites.json) that fetch_govpl.py consumes. |
| |
| gov.pl offers no sitemap or API for enumeration, and news-section slugs are |
| non-uniform: ministries use `/aktualnosci`, but voivodeship/agency subsites use |
| `/wiadomosci2`, `/aktualnosci10`, `/wszystkie-aktualnosci`, etc. (gov.pl appends |
| numeric suffixes to disambiguate repeated slugs). So discovery is a separate, |
| auditable step — freeze the JS-rendered subsite list, then probe each landing |
| page for its deepest-paginating news section. fetch_govpl.py then reads the |
| manifest with plain stdlib (no browser), keeping the fetch reproducible. |
| |
| SEED_SLUGS was captured from the rendered catalog at |
| https://www.gov.pl/web/gov/katalog-jednostek on 2026-07-18 (a client-side list, |
| NOT fetchable over plain HTTP). To refresh, open that page in a browser console |
| and run: |
| [...new Set([...document.querySelectorAll('a[href*="/web/"]')] |
| .map(a => (a.getAttribute('href').match(/\\/web\\/([a-z0-9-]+)/i)||[])[1]) |
| .filter(Boolean))].filter(s => s !== 'gov') |
| then paste the array into SEED_SLUGS below. |
| |
| All gov.pl text is CC-BY-SA 4.0 (site footer), government-authored/hosted. |
| |
| Usage: |
| python3 src/discover_govpl.py --out src/govpl_subsites.json |
| """ |
| from __future__ import annotations |
| import argparse, http.client, json, re, time |
| from datetime import date |
| from html import unescape |
| from urllib.request import urlopen, Request |
| from urllib.error import URLError, HTTPError |
|
|
| BASE = "https://www.gov.pl" |
| UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)", |
| "Accept": "text/html"} |
|
|
| |
| SEED_SLUGS = [ |
| "premier", "aktywa-panstwowe", "cyfryzacja", "edukacja", "energia", |
| "finanse", "fundusze-regiony", "infrastruktura", "klimat", "kultura", |
| "nauka", "obrona-narodowa", "rodzina", "rolnictwo", "rozwoj-technologia", |
| "sport", "sprawiedliwosc", "mswia", "dyplomacja", "zdrowie", "zermswia", |
| "arimr", "chemikalia", "rpp", "gdos", "gif", "piorin", "gios", "gis", |
| "gitd", "gugik", "krus", "paa", "rcb", "udsc", "prokuratoria", "urpl", |
| "uzp", "uw-kujawsko-pomorski", "uw-lubelski", "uw-lubuski", "uw-lodzki", |
| "uw-mazowiecki", "uw-opolski", "uw-podkarpacki", "uw-podlaski", |
| "uw-warminsko-mazurski", "uw-zachodniopomorski", "gddkia-bialystok", |
| "gddkia-bydgoszcz", "gddkia-gdansk", "gddkia-katowice", "gddkia-kielce", |
| "gddkia-krakow", "gddkia-lublin", "gddkia-lodz", "gddkia-olsztyn", |
| "gddkia-opole", "gddkia-poznan", "gddkia-rzeszow", "gddkia-szczecin", |
| "gddkia-warszawa", "gddkia-wroclaw", "gddkia-zielona-gora", "wsse-bialystok", |
| "wsse-bydgoszcz", "wsse-gdansk", "wsse-gorzowwlkp", "wsse-katowice", |
| "wsse-kielce", "wsse-krakow", "wsse-lublin", "wsse-lodz", "wsse-olsztyn", |
| "wsse-opole", "wsse-poznan", "wsse-rzeszow", "wsse-szczecin", |
| "wsse-warszawa", "wsse-wroclaw", "prokuratura-krajowa", "po-bialystok", |
| "po-bielsko-biala", "po-bydgoszcz", "po-elblag", "po-gdansk", "po-gliwice", |
| "po-gorzow-wielkopolski", "po-katowice", "po-kielce", "po-krakow", |
| "po-legnica", "po-lublin", "po-lodz", "po-lomza", "po-nowy-sacz", |
| "po-olsztyn", "po-opole", "po-ostroleka", "po-ostrow-wielkopolski", |
| "po-piotrkow-trybunalski", "po-plock", "po-poznan", "po-rzeszow", |
| "po-siedlce", "po-sieradz", "po-slupsk", "po-sosnowiec", "po-swidnica", |
| "po-tarnobrzeg", "po-tarnow", "po-torun", "po-warszawa", "po-warszawa-praga", |
| "po-wloclawek", "po-wroclaw", "po-zielona-gora", "pr-gdansk", "pr-katowice", |
| "pr-krakow", "pr-lublin", "pr-lodz", "pr-poznan", "pr-rzeszow", |
| "pr-szczecin", "pr-warszawa", "pr-wroclaw", "kgpsp", "kwpsp-gdansk", |
| "kwpsp-opole", "kwpsp-poznan", "cskmswia", "spzoz-mswia-katowice", |
| "spzoz-mswia-lublin", "spzoz-mswia-opole", "spzoz-mswia-szczecin", |
| "spzoz-mswia-zielona-gora", "spzoz-mswia-glucholazy", "krrit", "kowr", |
| "kzn", "nck", "wody-polskie", |
| ] |
|
|
| |
| |
| _NEWS_PREFIX = re.compile(r"^(wszystkie-aktualnosci|aktualnosci|wiadomosci|" |
| r"serwis-prasowy|komunikaty)", re.I) |
| |
| |
| |
| _ARTICLE = re.compile( |
| r'<span class="date">\s*([\d.]+)\s*</span>.*?' |
| r'<div class="title">\s*<a href="([^"]+)"[^>]*>\s*(.*?)\s*</a>', |
| re.I | re.S) |
| _PAGE = re.compile(r'[?&]page=(\d+)') |
|
|
|
|
| def http_get_url(url: str, tries: int = 4) -> tuple[str | None, str]: |
| """GET, returning (text, final_url_after_redirects). text is None on 404 or |
| exhausted retries. Needed because gov.pl news aliases (e.g. /aktualnosci) |
| 302-redirect to a canonical feed (/wydarzenia) and DROP the ?page= param — |
| so pagination must run against the resolved canonical URL, not the alias.""" |
| for i in range(tries): |
| try: |
| with urlopen(Request(url, headers=UA), timeout=60) as r: |
| return r.read().decode("utf-8", "replace"), r.geturl() |
| |
| |
| except (HTTPError, OSError, http.client.HTTPException) as e: |
| if isinstance(e, HTTPError) and e.code == 404: |
| return None, url |
| time.sleep(1.5 * (i + 1)) |
| return None, url |
|
|
|
|
| def http_get(url: str, tries: int = 4) -> str | None: |
| """GET text, retrying transient errors; None on 404 or exhausted retries.""" |
| return http_get_url(url, tries)[0] |
|
|
|
|
| def listing_articles(html: str, slug: str) -> list[dict]: |
| """{url,title,date} for real articles on a listing page of subsite `slug`.""" |
| out = [] |
| prefix = f"/web/{slug}/" |
| for date_str, href, title in _ARTICLE.findall(html): |
| if href.startswith(prefix): |
| out.append({ |
| "url": href, |
| "title": unescape(re.sub(r"\s+", " ", title)).strip(), |
| "date": date_str, |
| }) |
| return out |
|
|
|
|
| def max_page(html: str) -> int: |
| nums = [int(n) for n in _PAGE.findall(html)] |
| return max(nums) if nums else 1 |
|
|
|
|
| def news_candidates(landing_html: str, slug: str) -> list[str]: |
| """Distinct same-subsite sub-slugs that look like a news section.""" |
| seen = {} |
| for sub in re.findall(rf'href="/web/{re.escape(slug)}/([a-z0-9-]+)"', landing_html): |
| if _NEWS_PREFIX.match(sub): |
| seen[sub] = True |
| return list(seen) |
|
|
|
|
| def probe_subsite(slug: str) -> dict | None: |
| """Resolve a subsite's best news section -> {slug, news_path, pages} or None.""" |
| landing = http_get(f"{BASE}/web/{slug}") |
| if not landing: |
| return None |
| best = None |
| for sub in news_candidates(landing, slug): |
| html = http_get(f"{BASE}/web/{slug}/{sub}") |
| if not html: |
| continue |
| n_art = len(listing_articles(html, slug)) |
| if n_art == 0: |
| continue |
| pages = max_page(html) |
| |
| key = (pages, -len(sub)) |
| if best is None or key > best[0]: |
| best = (key, sub, pages) |
| time.sleep(0.2) |
| if best is None: |
| return None |
| return {"slug": slug, "news_path": best[1], "pages": best[2]} |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--out", default="src/govpl_subsites.json") |
| ap.add_argument("--slugs", nargs="*", help="override SEED_SLUGS (for testing)") |
| args = ap.parse_args() |
|
|
| slugs = args.slugs or SEED_SLUGS |
| manifest, skipped = [], [] |
| for i, slug in enumerate(slugs, 1): |
| rec = probe_subsite(slug) |
| if rec: |
| manifest.append(rec) |
| print(f"[{i}/{len(slugs)}] {slug} -> {rec['news_path']} ({rec['pages']}p)", flush=True) |
| else: |
| skipped.append(slug) |
| print(f"[{i}/{len(slugs)}] {slug} -> NO NEWS SECTION (skipped)", flush=True) |
|
|
| total_pages = sum(r["pages"] for r in manifest) |
| out = { |
| "generated": date.today().isoformat(), |
| "source": f"{BASE}/web/gov/katalog-jednostek", |
| "subsites": manifest, |
| "skipped": skipped, |
| "total_pages": total_pages, |
| } |
| with open(args.out, "w", encoding="utf-8") as f: |
| json.dump(out, f, ensure_ascii=False, indent=2) |
| print(f"\nwrote {args.out}: {len(manifest)} subsites, {total_pages} listing pages, " |
| f"{len(skipped)} skipped") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|