195 lines
8.9 KiB
Python
Executable File
195 lines
8.9 KiB
Python
Executable File
"""Scraper portal berita: ANTARA, Detik.com, CNN Indonesia.
|
|
|
|
CATATAN: struktur HTML & URL pencarian portal bisa berubah kapan saja. Modul ini tidak bergantung pada CSS
|
|
selector yang rapuh: tautan artikel dicari dengan pola URL (absolut maupun relatif), metadata diambil dari
|
|
<meta>/JSON-LD, dan isi artikel dicoba lewat beberapa selector umum. Gunakan scripts/debug_portal.py untuk
|
|
memeriksa tiap portal, dan patuhi robots.txt serta syarat penggunaan situs."""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
from collections import Counter
|
|
from datetime import date, datetime
|
|
from urllib.parse import quote_plus, urljoin
|
|
|
|
from bs4 import BeautifulSoup
|
|
|
|
from ingestion.common import build_record, parse_date_any
|
|
|
|
PORTALS = {
|
|
"antara": {
|
|
"name": "ANTARA",
|
|
"search": "https://www.antaranews.com/search?q={q}&page={page}",
|
|
"link_re": re.compile(r"https?://(?:www\.)?antaranews\.com/berita/\d+/[^\s\"'#?]+"),
|
|
},
|
|
"detik": {
|
|
"name": "Detik.com",
|
|
"search": "https://www.detik.com/search/searchall?query={q}&page={page}&result_type=latest",
|
|
"link_re": re.compile(r"https?://[a-z0-9.\-]*detik\.com/[^\s\"'#?]*?/d-\d+/[^\s\"'#?]+"),
|
|
},
|
|
"cnn": {
|
|
"name": "CNN Indonesia",
|
|
# Halaman pencarian CNN tidak berisi tautan artikel (dirender JavaScript); halaman tag berisi.
|
|
"search": "https://www.cnnindonesia.com/tag/{q}?page={page}",
|
|
"query_style": "slug",
|
|
"link_re": re.compile(r"https?://(?:www\.)?cnnindonesia\.com/[a-z0-9\-]+/\d{14}-\d+-\d+/[^\s\"'#?]+"),
|
|
},
|
|
}
|
|
|
|
# Hasil pencarian portal sering memuat berita tak terkait (sidebar, terpopuler). Tautan yang slug-nya tidak
|
|
# memuat salah satu petunjuk ini dilewati agar tidak membuka ratusan halaman sia-sia.
|
|
SLUG_SUBSTR = ["karhutla", "karlahut", "kebakaran", "bakar", "hutan", "lahan", "gambut", "kabut", "padam",
|
|
"hotspot", "ispu", "titik-panas", "titik-api", "water-bombing", "modifikasi-cuaca"]
|
|
SLUG_TOKENS = {"api", "asap"} # kata pendek: harus berdiri sendiri ('api', bukan 'rapi')
|
|
|
|
_DATE_META = [
|
|
("property", r"^article:published_time$"), ("name", r"^(content_)?publishdate$"),
|
|
("name", r"^content_publisheddate$"), ("itemprop", r"^datePublished$"),
|
|
("name", r"^pubdate$"), ("property", r"^og:updated_time$"),
|
|
]
|
|
|
|
_BODY_SELECTORS = ["[itemprop=articleBody]", "div.post-content", "div.detail__body-text", "div.detail-text",
|
|
"div.detail_text", "div.article-content", "div.entry-content", "article"]
|
|
_JUNK_SELECTORS = ["script", "style", "aside", "figure", "iframe", "noscript", ".parallaxindetail",
|
|
".staticdetail_container", ".detail__body-tag", ".baca-juga", ".related",
|
|
"[class*=advert]", "[class*=baca]", "[class*=terkait]"]
|
|
_JUNK_PREFIX = ("baca juga", "baca:", "advertisement", "scroll to continue", "simak juga", "lihat juga")
|
|
|
|
|
|
def extract_links(html: str, base_url: str, link_re: re.Pattern) -> list[str]:
|
|
"""Tautan artikel dari halaman: dari atribut href (absolut/relatif) dan URL absolut di teks mentah."""
|
|
cands = list(link_re.findall(html))
|
|
for h in re.findall(r'href=["\']([^"\']+)["\']', html):
|
|
cands.append(urljoin(base_url, h.split("#")[0]))
|
|
out = []
|
|
for u in cands:
|
|
m = link_re.match(u.split("?")[0])
|
|
if m:
|
|
out.append(m.group(0))
|
|
return list(dict.fromkeys(out))
|
|
|
|
|
|
def slug_relevant(url: str) -> bool:
|
|
low = url.lower()
|
|
return any(h in low for h in SLUG_SUBSTR) or bool(SLUG_TOKENS & set(re.split(r"[^a-z0-9]+", low)))
|
|
|
|
|
|
def query_for(portal: dict, keyword: str) -> str:
|
|
"""Bentuk kata kunci di URL: 'karhutla+api' (pencarian) atau 'kebakaran-hutan' (halaman tag)."""
|
|
if portal.get("query_style") == "slug":
|
|
return re.sub(r"[^a-z0-9]+", "-", keyword.lower()).strip("-")
|
|
return quote_plus(keyword)
|
|
|
|
|
|
def discover_links(portal: dict, keyword: str, max_pages: int, session, sleep: float):
|
|
seen: set[str] = set()
|
|
for page in range(1, max_pages + 1):
|
|
url = portal["search"].format(q=query_for(portal, keyword), page=page)
|
|
try:
|
|
r = session.get(url, timeout=30)
|
|
r.raise_for_status()
|
|
except Exception as exc:
|
|
print(f"[{portal['name']}] gagal halaman pencarian {page} '{keyword}': {exc}", flush=True)
|
|
break
|
|
found = [u for u in extract_links(r.text, url, portal["link_re"]) if u not in seen]
|
|
if not found:
|
|
if page == 1:
|
|
print(f"[{portal['name']}] halaman pencarian 1 '{keyword}' (HTTP {r.status_code}, {len(r.text)} karakter) "
|
|
f"tidak berisi tautan artikel yang cocok. Jalankan scripts/debug_portal.py.", flush=True)
|
|
break
|
|
for u in found:
|
|
seen.add(u)
|
|
yield u
|
|
time.sleep(sleep)
|
|
|
|
|
|
def _extract_body(soup: BeautifulSoup) -> str:
|
|
for sel in _BODY_SELECTORS:
|
|
node = soup.select_one(sel)
|
|
if not node:
|
|
continue
|
|
for junk in node.select(",".join(_JUNK_SELECTORS)):
|
|
junk.decompose()
|
|
lines = [re.sub(r"\s+", " ", ln).strip() for ln in node.get_text("\n").split("\n")]
|
|
lines = [ln for ln in lines if len(ln) >= 40 and not ln.lower().startswith(_JUNK_PREFIX)]
|
|
text = " ".join(lines)
|
|
if len(text) >= 200:
|
|
return text[:20000]
|
|
paras = [p.get_text(" ", strip=True) for p in soup.find_all("p")]
|
|
paras = [p for p in paras if len(p) >= 40 and not p.lower().startswith(_JUNK_PREFIX)]
|
|
return " ".join(paras)[:20000]
|
|
|
|
|
|
def fetch_article(url: str, session, timeout: int = 30) -> dict:
|
|
"""Ambil judul, tanggal, dan isi dari satu halaman artikel. Bila gagal, kolom 'error' terisi."""
|
|
try:
|
|
r = session.get(url, timeout=timeout)
|
|
r.raise_for_status()
|
|
except Exception as exc:
|
|
status = getattr(getattr(exc, "response", None), "status_code", None)
|
|
return {"judul": "", "isi": "", "tanggal": None, "url": url, "raw_date": None, "date_source": None,
|
|
"html": "", "error": f"HTTP {status}" if status else type(exc).__name__}
|
|
soup = BeautifulSoup(r.text, "html.parser")
|
|
|
|
og = soup.find("meta", attrs={"property": "og:title"})
|
|
title = (og.get("content") if og and og.get("content") else (soup.h1.get_text(" ", strip=True) if soup.h1 else "")).strip()
|
|
|
|
raw_date, date_source = None, None
|
|
for attr, pattern in _DATE_META:
|
|
tag = soup.find("meta", attrs={attr: re.compile(pattern, re.I)})
|
|
if tag and tag.get("content"):
|
|
raw_date, date_source = tag["content"], f"meta[{attr}~{pattern}]"
|
|
break
|
|
if not raw_date:
|
|
m = re.search(r'"datePublished"\s*:\s*"([^"]+)"', r.text)
|
|
raw_date, date_source = (m.group(1), "json-ld datePublished") if m else (None, None)
|
|
if not raw_date:
|
|
t = soup.find("time", attrs={"datetime": True})
|
|
raw_date, date_source = (t["datetime"], "time[datetime]") if t else (None, None)
|
|
|
|
body = _extract_body(soup)
|
|
return {"judul": title, "isi": body, "tanggal": parse_date_any(raw_date), "url": url,
|
|
"raw_date": raw_date, "date_source": date_source, "html": r.text, "error": None}
|
|
|
|
|
|
def collect(portal_key: str, keywords, start: date, end: date, session,
|
|
max_pages: int = 5, sleep: float = 1.5, limit: int | None = None, slug_filter: bool = True):
|
|
portal = PORTALS[portal_key]
|
|
seen_urls: set[str] = set()
|
|
n = 0
|
|
diag: Counter = Counter()
|
|
try:
|
|
for kw in keywords:
|
|
for url in discover_links(portal, kw, max_pages, session, sleep):
|
|
if url in seen_urls:
|
|
continue
|
|
seen_urls.add(url)
|
|
diag["tautan_ditemukan"] += 1
|
|
if slug_filter and not slug_relevant(url):
|
|
diag["dilewati_slug_tak_relevan"] += 1
|
|
continue
|
|
art = fetch_article(url, session)
|
|
time.sleep(sleep)
|
|
if art.get("error"):
|
|
diag[f"gagal_buka ({art['error']})"] += 1
|
|
continue
|
|
if not art["tanggal"]:
|
|
diag["tanggal_tidak_terbaca"] += 1
|
|
if diag["tanggal_tidak_terbaca"] <= 2:
|
|
print(f"[{portal['name']}] tanggal tidak terbaca: {url} (raw={art['raw_date']!r})", flush=True)
|
|
continue
|
|
d = datetime.fromisoformat(art["tanggal"]).date()
|
|
if d < start or d > end:
|
|
diag["di_luar_rentang_tanggal"] += 1
|
|
continue
|
|
if not art["isi"]:
|
|
diag["isi_kosong (tetap disimpan)"] += 1
|
|
diag["diterima"] += 1
|
|
yield build_record(judul=art["judul"], url=url, tanggal=art["tanggal"], sumber=portal["name"],
|
|
sumber_data=portal_key, kata_kunci=kw, isi=art["isi"])
|
|
n += 1
|
|
if limit and n >= limit:
|
|
return
|
|
finally:
|
|
print(f"[{portal['name']}] ringkasan: {dict(diag) or 'tidak ada tautan artikel ditemukan'}", flush=True)
|