Datasets:
File size: 8,858 Bytes
87f5bc4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | #!/usr/bin/env python3
"""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"}
# Frozen JS-rendered catalog (see module docstring for refresh recipe).
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",
]
# A landing-page sub-page counts as a news section if its slug starts with one
# of these (gov.pl appends -suffix / digits, e.g. aktualnosci10, wiadomosci2).
_NEWS_PREFIX = re.compile(r"^(wszystkie-aktualnosci|aktualnosci|wiadomosci|"
r"serwis-prasowy|komunikaty)", re.I)
# On a listing page each article preview is an <span class="date"> ... </span>
# (inside a class="event" block) followed by <div class="title"><a href=...>.
# Binding the two in one match keeps date/title/url aligned per article.
_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()
# OSError covers URLError/TimeoutError/socket/ssl/ConnectionReset;
# HTTPException covers IncompleteRead (truncated body) — all transient, retry.
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)
# Prefer the deepest-paginating feed; tie-break the shorter (more general) slug.
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, # logged, not silently dropped
"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()
|