"""Small, auditable crawler for Faroese public-authority websites.""" from __future__ import annotations import argparse import csv import hashlib import io import json import re import time import unicodedata import xml.etree.ElementTree as ET from collections import deque from datetime import datetime, timezone from pathlib import Path from typing import TextIO from urllib.parse import parse_qsl, unquote, urlencode, urljoin, urlsplit, urlunsplit from urllib.robotparser import RobotFileParser import requests from bs4 import BeautifulSoup from docx import Document from pypdf import PdfReader SCRIPT_DIR = Path(__file__).resolve().parent DEFAULT_OUTPUT = SCRIPT_DIR / "output" USER_AGENT = "Faroese-Dynaword-Research-Crawler/1.0 (contact: dynaword@dfm.dk)" MAX_DOWNLOAD_BYTES = 100_000_000 SKIP_EXTENSIONS = { ".7z", ".avi", ".bmp", ".css", ".doc", ".eot", ".epub", ".exe", ".gif", ".gz", ".heic", ".heif", ".ico", ".jpeg", ".jpg", ".js", ".json", ".m4a", ".m4v", ".mov", ".mp3", ".mp4", ".mpeg", ".ods", ".odt", ".png", ".ppt", ".pptx", ".rar", ".rss", ".svg", ".tar", ".tif", ".tiff", ".ttf", ".wav", ".webm", ".webp", ".woff", ".woff2", ".xls", ".xlsm", ".xlsx", ".xml", ".zip", } DOCUMENT_EXTENSIONS = { ".csv", ".doc", ".docx", ".ods", ".odt", ".pdf", ".ppt", ".pptx", ".rtf", ".txt", ".xls", ".xlsx", } SUPPORTED_DOCUMENT_EXTENSIONS = {".csv", ".docx", ".pdf", ".txt"} TRACKING_PARAMETERS = { "fbclid", "gclid", "mc_cid", "mc_eid", "msclkid", "utm_campaign", "utm_content", "utm_medium", "utm_source", "utm_term", } FORMAL_WORDS = { "alit", "álit", "avgerd", "avgerð", "arsfragreiding", "ársfrágreiðing", "budget", "fjarlog", "fíggjarlog", "fragreiding", "frágreiðing", "fundarbok", "fundarbók", "fundarfragreiding", "fundarfrágreiðing", "hagtol", "hagtøl", "kanning", "kunngerd", "kunngerð", "log", "lóg", "niðurstøða", "reglugerd", "logasavn", "lógasavn", "logir", "lógir", "reglugerð", "samtykt", "tilmæli", "urskurd", "úrskurð", "vedtakt", } def lexical_key(value: str) -> str: decomposed = unicodedata.normalize("NFKD", value.casefold()) unaccented = "".join(character for character in decomposed if not unicodedata.combining(character)) return unaccented.replace("ð", "d").replace("ø", "o").replace("æ", "ae") FORMAL_KEYS = {lexical_key(word) for word in FORMAL_WORDS} def load_sites(path: Path) -> list[dict[str, str]]: with path.open(encoding="utf-8", newline="") as file: return list(csv.DictReader(file)) def clean_url(url: str) -> str: parts = urlsplit(url) if parts.scheme not in {"http", "https"}: return "" query = [ (key, value) for key, value in parse_qsl(parts.query, keep_blank_values=True) if key.lower() not in TRACKING_PARAMETERS ] path = re.sub(r"/{2,}", "/", parts.path or "/") return urlunsplit((parts.scheme.lower(), parts.netloc.lower(), path, urlencode(query), "")) def host_key(url: str) -> str: return (urlsplit(url).hostname or "").lower().removeprefix("www.") def should_visit(url: str, allowed_hosts: set[str]) -> bool: if not url or host_key(url) not in allowed_hosts: return False if any(character in url for character in '<>"{}'): # Some CMS fields contain a whole iframe fragment where an href should # be. Treating that fragment as a relative URL only creates fake 4xx # requests on the site's own hostname. return False path = urlsplit(url).path.lower() suffix = Path(path).suffix if suffix in SUPPORTED_DOCUMENT_EXTENSIONS: return True if suffix in SKIP_EXTENSIONS: return False lowered = url.lower() blocked_parts = ( "/api/", "/login", "/logout", "/signin", "/wp-admin", "/xmlrpc.php", "mailto:", "javascript:", "share=", "add-to-calendar", ) return not any(part in lowered for part in blocked_parts) def is_document_url(url: str) -> bool: return Path(urlsplit(url).path.lower()).suffix in DOCUMENT_EXTENSIONS def configured_hosts(site: dict[str, str]) -> set[str]: hosts = {host_key(site["start_url"])} hosts.update( host.strip().lower().removeprefix("www.") for host in (site.get("allowed_hosts") or "").split("|") if host.strip() ) return hosts def write_json_line(file: TextIO, row: dict[str, object]) -> None: file.write(json.dumps(row, ensure_ascii=False) + "\n") def get_robots(session: requests.Session, start_url: str) -> RobotFileParser | None: parts = urlsplit(start_url) robots_url = urlunsplit((parts.scheme, parts.netloc, "/robots.txt", "", "")) try: response = fetch(session, robots_url) content = response_bytes(response) response.close() parser = RobotFileParser() parser.set_url(robots_url) parser.parse(content.decode(response.encoding or "utf-8", errors="replace").splitlines()) return parser except requests.RequestException: return None def fetch( session: requests.Session, url: str, headers: dict[str, str] | None = None, ) -> requests.Response: """Fetch a URL, retrying a few ordinary network failures.""" last_error: Exception | None = None for attempt in range(3): try: response = session.get(url, headers=headers, timeout=(15, 60), stream=True) except requests.RequestException as error: last_error = error if attempt < 2: time.sleep(2 * (attempt + 1)) continue if response.status_code == 429 or response.status_code >= 500: last_error = requests.HTTPError(f"HTTP {response.status_code}", response=response) response.close() if attempt < 2: time.sleep(2 * (attempt + 1)) continue response.raise_for_status() return response assert last_error is not None raise last_error def response_bytes(response: requests.Response) -> bytes: """Read a response without allowing one file to consume unbounded space.""" content_length = int(response.headers.get("Content-Length", 0) or 0) if content_length > MAX_DOWNLOAD_BYTES: raise ValueError(f"Response is larger than {MAX_DOWNLOAD_BYTES} bytes") chunks: list[bytes] = [] bytes_read = 0 for chunk in response.iter_content(chunk_size=1_000_000): bytes_read += len(chunk) if bytes_read > MAX_DOWNLOAD_BYTES: raise ValueError(f"Response is larger than {MAX_DOWNLOAD_BYTES} bytes") chunks.append(chunk) return b"".join(chunks) def fetch_content( session: requests.Session, url: str, allowed_hosts: set[str], ) -> tuple[requests.Response, bytes | None]: """Fetch a body, resuming ordinary interrupted downloads when supported.""" last_error: requests.RequestException | None = None content = bytearray() expected_total = 0 for attempt in range(12): headers = {"Range": f"bytes={len(content)}-"} if content else None response = fetch(session, url, headers=headers) if host_key(response.url) not in allowed_hosts: return response, None if content and response.status_code != 206: content.clear() content_encoding = response.headers.get("Content-Encoding", "").lower() encoded_response = content_encoding not in {"", "identity"} content_range = response.headers.get("Content-Range", "") range_match = re.search(r"/(\d+)$", content_range) if encoded_response: # Requests transparently decompresses these bodies, so the wire # Content-Length cannot be compared with the decoded byte count. expected_total = 0 elif range_match: expected_total = int(range_match.group(1)) else: content_length = int(response.headers.get("Content-Length", 0) or 0) expected_total = len(content) + content_length if content_length else 0 if expected_total > MAX_DOWNLOAD_BYTES: response.close() raise ValueError(f"Response is larger than {MAX_DOWNLOAD_BYTES} bytes") try: for chunk in response.iter_content(chunk_size=1_000_000): content.extend(chunk) if len(content) > MAX_DOWNLOAD_BYTES: raise ValueError( f"Response is larger than {MAX_DOWNLOAD_BYTES} bytes" ) if expected_total and len(content) != expected_total: raise requests.exceptions.ChunkedEncodingError( f"Expected {expected_total} bytes, received {len(content)}" ) return response, bytes(content) except requests.RequestException as error: last_error = error response.close() if encoded_response: # Byte ranges apply to the encoded representation, while the # accumulated buffer is decoded. Restart compressed responses. content.clear() if attempt < 11: time.sleep(min(2 * (attempt + 1), 5)) except ValueError: response.close() raise assert last_error is not None raise last_error def sitemap_urls( session: requests.Session, start_url: str, robots: RobotFileParser | None, ) -> list[str]: """Read ordinary XML sitemaps. Failure simply falls back to link crawling.""" parts = urlsplit(start_url) default_sitemap = urlunsplit((parts.scheme, parts.netloc, "/sitemap.xml", "", "")) sitemap_index = urlunsplit( (parts.scheme, parts.netloc, "/sitemap_index.xml", "", "") ) wordpress_sitemap = urlunsplit( (parts.scheme, parts.netloc, "/wp-sitemap.xml", "", "") ) advertised = robots.site_maps() if robots and robots.site_maps() else [] # Some sites advertise a stale sitemap in robots.txt while their standard # WordPress/Yoast endpoint contains the real archive. Trying all three is # cheap, read-only, and avoids silently reducing discovery to navigation. pending = deque([*advertised, default_sitemap, sitemap_index, wordpress_sitemap]) seen_sitemaps: set[str] = set() pages: list[str] = [] while pending and len(seen_sitemaps) < 100: sitemap_url = pending.popleft() if sitemap_url in seen_sitemaps: continue seen_sitemaps.add(sitemap_url) try: response = fetch(session, sitemap_url) content = response_bytes(response) response.close() # A few Faroese WordPress sites put a blank line before their XML # declaration. XML parsers reject that harmless formatting quirk. root = ET.fromstring(content.lstrip()) except (requests.RequestException, ET.ParseError, ValueError): continue locations = [element.text.strip() for element in root.iter() if element.tag.endswith("loc") and element.text] if root.tag.endswith("sitemapindex"): pending.extend(locations) else: pages.extend(locations) return pages def visible_html_text( content: bytes, encoding: str | None, ) -> tuple[str, str, list[str], str]: soup = BeautifulSoup(content, "html.parser", from_encoding=encoding) title = soup.title.get_text(" ", strip=True) if soup.title else "" canonical_element = soup.find("link", rel="canonical", href=True) canonical_url = canonical_element.get("href", "") if canonical_element else "" for element in soup(["script", "style", "noscript", "svg", "template"]): element.decompose() text = "" candidates = [soup.find("main"), soup.find("article"), soup.body, soup] for candidate in candidates: if candidate is None: continue candidate_text = candidate.get_text("\n", strip=True) candidate_text = re.sub(r"[ \t]+", " ", candidate_text) candidate_text = re.sub(r"\n{3,}", "\n\n", candidate_text).strip() text = candidate_text if len(text) >= 100: break links = [link.get("href", "") for link in soup.find_all("a", href=True)] return title, text, links, canonical_url def site_url(site: dict[str, str], url: str) -> str: """Clean one discovered URL, including documented CMS quirks.""" cleaned = clean_url(url) parts = urlsplit(cleaned) if site["slug"] == "irf_fo" and parts.netloc == "www.irf.fo": # The www hostname presents a mismatched certificate; the same pages are # publicly served at IRF's canonical bare hostname. parts = parts._replace(netloc="irf.fo") cleaned = urlunsplit(parts) page_match = re.search(r"/page/(\d+)/?$", parts.path) if site["slug"] == "fuglafjordur_fo" and page_match: # Fuglafjordur's news widget appends /page/N to every article URL. All # those paths declare the article without /page/N as canonical, while # the actual paginated news archive is /news/page/N/. if not re.fullmatch(r"/news/page/\d+/?", parts.path): path = f"/news/page/{page_match.group(1)}/" return urlunsplit((parts.scheme, parts.netloc, path, "", "")) if site["slug"] == "irf_fo" and page_match: # IRF's WordPress pagination links are also rendered inside individual # articles, producing /article/page/N URLs whose canonical target is # the unpaginated article. Preserve genuine root and news-archive # pagination; IRF's news archive lives at /tidindi/page/N/. article_path = parts.path[: page_match.start()] or "/" if article_path.rstrip("/") not in {"", "/tidindi"}: article_path = f"{article_path.rstrip('/')}/" return urlunsplit( (parts.scheme, parts.netloc, article_path, parts.query, "") ) if site["slug"] == "fma_fo" and page_match: # FMA's theme inserts global pager links into individual articles and # service pages. WordPress serves those /page/N variants with the # unpaginated page as canonical. Preserve only the genuine news-list # pagination routes. article_path = parts.path[: page_match.start()] or "/" if article_path.rstrip("/") not in {"/news", "/news-en"}: article_path = f"{article_path.rstrip('/')}/" return urlunsplit( (parts.scheme, parts.netloc, article_path, parts.query, "") ) return cleaned def pdf_text(content: bytes) -> tuple[str, str]: reader = PdfReader(io.BytesIO(content)) pages = [(page.extract_text() or "").strip() for page in reader.pages] text = "\n\n".join(page for page in pages if page) title = "" if reader.metadata and reader.metadata.title: title = str(reader.metadata.title).strip() return title, text def docx_text(content: bytes) -> tuple[str, str]: document = Document(io.BytesIO(content)) blocks = [paragraph.text.strip() for paragraph in document.paragraphs] for table in document.tables: for row in table.rows: blocks.append("\t".join(cell.text.strip() for cell in row.cells)) text = "\n".join(block for block in blocks if block).strip() title = (document.core_properties.title or "").strip() return title, text def plain_text(content: bytes, encoding: str | None, url: str) -> tuple[str, str]: text = content.decode(encoding or "utf-8", errors="replace").strip() return Path(urlsplit(url).path).name, text def looks_like_mislabelled_binary(content: bytes, content_type: str) -> bool: if content_type not in {"", "application/xhtml+xml", "text/html", "text/plain"}: return False return ( content.startswith(b"\x89PNG\r\n\x1a\n") or content.startswith(b"PK\x03\x04") or content[4:12] in {b"ftypheic", b"ftypheix", b"ftypmif1"} ) def rights_status(title: str, url: str, content_type: str) -> str: searchable = lexical_key(f"{title} {unquote(url)}") words = set(re.findall(r"[^\W_]+", searchable)) if words & FORMAL_KEYS or any( len(marker) >= 5 and word.startswith(marker) for word in words for marker in FORMAL_KEYS ): return "likely_official_document" if content_type == "application/pdf": return "review_pdf" if content_type != "text/html": return "review_document" return "review_general_web_content" def rights_basis(status: str) -> str: if status == "likely_official_document": return ( "Filename/title screening suggests a possible official-document " "copyright exclusion under section 9 of Faroese Copyright Act No. 30 " "of 30 April 2015; issuing authority, document type, independent " "contributions, privacy, and database rights still require review" ) return ( "No site-wide open licence was identified and the section 9 " "official-document exclusion has not been established for this row; " "do not redistribute without document-level review or permission" ) def make_row( site: dict[str, str], requested_url: str, final_url: str, content_type: str, title: str, text: str, ) -> dict[str, str | int]: status = rights_status(title, final_url, content_type) return { "source_site": site["slug"], "source_homepage": site["start_url"], "source_url": final_url, "requested_url": requested_url, "retrieved_at": datetime.now(timezone.utc).isoformat(), "content_type": content_type, "title": title, "text": text, "text_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), "text_characters": len(text), "rights_status": status, "rights_basis": rights_basis(status), } def crawl_site( site: dict[str, str], output_root: Path, max_pages: int, delay: float, minimum_characters: int, ) -> None: site_dir = output_root / site["slug"] site_dir.mkdir(parents=True, exist_ok=True) rows_path = site_dir / "rows.jsonl" errors_path = site_dir / "errors.jsonl" requests_path = site_dir / "requests.jsonl" external_documents_path = site_dir / "external_documents.jsonl" report_path = site_dir / "crawl_report.json" session = requests.Session() session.headers["User-Agent"] = USER_AGENT start_url = site_url(site, site["start_url"]) visited: set[str] = set() home_host = host_key(start_url) allowed_hosts = configured_hosts(site) robots = get_robots(session, start_url) discovered = [start_url] discovered.extend((site.get("seed_urls") or "").split("|")) discovered.extend(sitemap_urls(session, start_url, robots)) queue = deque( url for url in (site_url(site, url) for url in discovered) if should_visit(url, allowed_hosts) ) queued = set(queue) rows_written = 0 duplicate_texts = 0 skipped_short = 0 skipped_robots = 0 skipped_external_redirects = 0 errors = 0 external_documents: set[str] = set() text_hashes: set[str] = set() started_at = datetime.now(timezone.utc).isoformat() with ( rows_path.open("w", encoding="utf-8") as rows_file, errors_path.open("w", encoding="utf-8") as errors_file, requests_path.open("w", encoding="utf-8") as requests_file, external_documents_path.open("w", encoding="utf-8") as external_documents_file, ): while queue and len(visited) < max_pages: requested_url = queue.popleft() if requested_url in visited: continue visited.add(requested_url) time.sleep(delay) if ( host_key(requested_url) == home_host and robots and not robots.can_fetch(USER_AGENT, requested_url) ): skipped_robots += 1 write_json_line( requests_file, {"requested_url": requested_url, "outcome": "robots_disallowed"}, ) continue try: response, content = fetch_content(session, requested_url, allowed_hosts) status_code = response.status_code final_url = clean_url(response.url) if host_key(final_url) not in allowed_hosts: skipped_external_redirects += 1 response.close() write_json_line( requests_file, { "requested_url": requested_url, "final_url": final_url, "status_code": status_code, "outcome": "external_redirect", }, ) continue assert content is not None content_type = response.headers.get("Content-Type", "").split(";", 1)[0].lower() if looks_like_mislabelled_binary(content, content_type): response.close() write_json_line( requests_file, { "requested_url": requested_url, "final_url": final_url, "status_code": status_code, "content_type": content_type, "outcome": "mislabelled_binary", }, ) continue if content_type == "application/pdf" or final_url.lower().endswith(".pdf"): title, text = pdf_text(content) content_type = "application/pdf" links: list[str] = [] elif ( content_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" or urlsplit(final_url).path.lower().endswith(".docx") ): title, text = docx_text(content) content_type = ( "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) links = [] elif ( content_type in {"text/csv", "text/plain"} or urlsplit(final_url).path.lower().endswith((".csv", ".txt")) ): title, text = plain_text(content, response.encoding, final_url) content_type = ( "text/csv" if urlsplit(final_url).path.lower().endswith(".csv") else "text/plain" ) links = [] elif content_type in {"text/html", "application/xhtml+xml", ""}: title, text, links, canonical_href = visible_html_text( content, response.encoding ) canonical_url = site_url(site, urljoin(final_url, canonical_href)) if canonical_url and host_key(canonical_url) in allowed_hosts: final_url = canonical_url content_type = "text/html" else: response.close() write_json_line( requests_file, { "requested_url": requested_url, "final_url": final_url, "status_code": status_code, "content_type": content_type, "outcome": "unsupported_content", }, ) continue response.close() for href in links: candidate = site_url(site, urljoin(final_url, href)) if ( candidate and host_key(candidate) not in allowed_hosts and is_document_url(candidate) and candidate not in external_documents ): external_documents.add(candidate) write_json_line( external_documents_file, {"source_page_url": final_url, "document_url": candidate}, ) if candidate not in queued and should_visit(candidate, allowed_hosts): queue.append(candidate) queued.add(candidate) if len(text) < minimum_characters: skipped_short += 1 write_json_line( requests_file, { "requested_url": requested_url, "final_url": final_url, "status_code": status_code, "content_type": content_type, "outcome": "short_text", }, ) continue row = make_row(site, requested_url, final_url, content_type, title, text) text_hash = str(row["text_sha256"]) if text_hash in text_hashes: duplicate_texts += 1 write_json_line( requests_file, { "requested_url": requested_url, "final_url": final_url, "status_code": status_code, "content_type": content_type, "outcome": "duplicate_text", }, ) continue text_hashes.add(text_hash) write_json_line(rows_file, row) rows_written += 1 write_json_line( requests_file, { "requested_url": requested_url, "final_url": final_url, "status_code": status_code, "content_type": content_type, "outcome": "row_written", }, ) except Exception as error: errors += 1 error_row = {"source_url": requested_url, "error": repr(error)} write_json_line(errors_file, error_row) write_json_line( requests_file, { "requested_url": requested_url, "outcome": "error", "error": repr(error), }, ) report = { "site": site, "started_at": started_at, "finished_at": datetime.now(timezone.utc).isoformat(), "max_pages": max_pages, "pages_requested": len(visited), "rows_written": rows_written, "duplicate_texts_skipped": duplicate_texts, "short_pages_skipped": skipped_short, "robots_disallowed_skipped": skipped_robots, "external_redirects_skipped": skipped_external_redirects, "external_document_links_found": len(external_documents), "errors": errors, "remaining_queue": len(queue), "complete_within_discovered_links": len(queue) == 0, } report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(json.dumps(report, ensure_ascii=False)) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--sites", type=Path, default=SCRIPT_DIR / "sites.csv") parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) parser.add_argument("--site", action="append", help="Only crawl this site slug; repeatable") parser.add_argument("--max-pages", type=int, default=25_000) parser.add_argument("--delay", type=float, default=0.25) parser.add_argument("--minimum-characters", type=int, default=100) args = parser.parse_args() sites = load_sites(args.sites) if args.site: selected = set(args.site) if "posta_fo" in selected: raise SystemExit( "posta_fo uses scrape_posta.py because the public site is an Angular shell" ) sites = [site for site in sites if site["slug"] in selected] missing = selected - {site["slug"] for site in sites} if missing: raise SystemExit(f"Unknown site slug(s): {', '.join(sorted(missing))}") else: sites = [site for site in sites if site["slug"] != "posta_fo"] args.output.mkdir(parents=True, exist_ok=True) for site in sites: crawl_site(site, args.output, args.max_pages, args.delay, args.minimum_characters) if __name__ == "__main__": main()