92 lines
4.0 KiB
Python
92 lines
4.0 KiB
Python
"""Diagnostik scraper portal: lihat apa yang sebenarnya dikembalikan situs, dan simpan HTML-nya.
|
|
docker compose exec pipeline python scripts/debug_portal.py antara detik cnn
|
|
Hasil HTML: data/reports/debug_<portal>_search.html dan debug_<portal>_article.html"""
|
|
import re
|
|
import sys
|
|
|
|
import config
|
|
from ingestion import portals
|
|
from ingestion.common import make_session
|
|
|
|
# URL alternatif yang ikut diuji bila halaman pencarian utama tidak menghasilkan tautan artikel
|
|
ALTERNATIVES = {
|
|
"cnn": ["https://www.cnnindonesia.com/tag/karhutla", "https://www.cnnindonesia.com/tag/kebakaran-hutan",
|
|
"https://www.cnnindonesia.com/search?query=karhutla"],
|
|
"detik": ["https://www.detik.com/tag/karhutla"],
|
|
"antara": ["https://www.antaranews.com/tag/karhutla"],
|
|
}
|
|
ASSET = re.compile(r"\.(css|js|png|jpe?g|gif|svg|ico|webp|woff2?|xml|json)(\?|$)", re.I)
|
|
|
|
|
|
def looks_like_article(href: str) -> bool:
|
|
path = href.split("?")[0].split("#")[0]
|
|
path = re.sub(r"^https?://[^/]+", "", path)
|
|
return not ASSET.search(href) and path.count("/") >= 2 and bool(re.search(r"\d{5,}", path))
|
|
|
|
|
|
def probe(url: str, portal: dict, session, save_as: str | None = None):
|
|
try:
|
|
r = session.get(url, timeout=30)
|
|
except Exception as exc:
|
|
print(f" GAGAL request {url}: {type(exc).__name__}: {exc}")
|
|
return None, []
|
|
if save_as:
|
|
(config.REPORT_DIR / save_as).write_text(r.text, encoding="utf-8")
|
|
links = portals.extract_links(r.text, url, portal["link_re"])
|
|
print(f" {url}\n HTTP {r.status_code} | {len(r.text)} karakter | tautan artikel cocok pola: {len(links)}")
|
|
return r, links
|
|
|
|
|
|
def debug(key: str, session, keyword: str = "karhutla"):
|
|
portal = portals.PORTALS[key]
|
|
url = portal["search"].format(q=portals.query_for(portal, keyword), page=1)
|
|
print(f"\n=== {portal['name']} ===")
|
|
config.REPORT_DIR.mkdir(parents=True, exist_ok=True)
|
|
r, links = probe(url, portal, session, save_as=f"debug_{key}_search.html")
|
|
if r is None:
|
|
return
|
|
for u in links[:5]:
|
|
print(" ", u)
|
|
relevan = [u for u in links if portals.slug_relevant(u)]
|
|
print(f" dari {len(links)} tautan, {len(relevan)} lolos filter slug (yang akan dibuka)")
|
|
|
|
if not links:
|
|
hrefs = list(dict.fromkeys(re.findall(r'href=["\']([^"\']+)["\']', r.text)))
|
|
cand = [h for h in hrefs if looks_like_article(h)]
|
|
print(f" href yang tampak seperti artikel ({len(cand)} dari {len(hrefs)} href), 15 contoh:")
|
|
for h in cand[:15]:
|
|
print(" ", h[:150])
|
|
print(" Mencoba URL alternatif:")
|
|
for alt in ALTERNATIVES.get(key, []):
|
|
r2, l2 = probe(alt, portal, session, save_as=f"debug_{key}_alt{ALTERNATIVES[key].index(alt)}.html")
|
|
for u in l2[:3]:
|
|
print(" ", u)
|
|
return
|
|
|
|
# cek pagination: halaman 2 dan 3 harus memuat tautan BARU
|
|
seen = set(links)
|
|
for pg in (2, 3):
|
|
u = portal["search"].format(q=portals.query_for(portal, keyword), page=pg)
|
|
try:
|
|
rp = session.get(u, timeout=30)
|
|
new = [x for x in portals.extract_links(rp.text, u, portal["link_re"]) if x not in seen]
|
|
seen.update(new)
|
|
print(f" halaman {pg}: HTTP {rp.status_code}, tautan baru: {len(new)}")
|
|
except Exception as exc:
|
|
print(f" halaman {pg}: gagal ({type(exc).__name__})")
|
|
|
|
art = portals.fetch_article(relevan[0] if relevan else links[0], session)
|
|
(config.REPORT_DIR / f"debug_{key}_article.html").write_text(art.get("html", ""), encoding="utf-8")
|
|
print(f"\n Artikel contoh: {art['url']}")
|
|
print(f" error : {art.get('error')}")
|
|
print(f" judul : {art['judul'][:100]!r}")
|
|
print(f" tanggal raw: {art['raw_date']!r} (sumber: {art['date_source']}) -> terbaca: {art['tanggal']}")
|
|
print(f" panjang isi: {len(art['isi'])} karakter | awal isi: {art['isi'][:120]!r}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
keys = sys.argv[1:] or list(portals.PORTALS)
|
|
s = make_session()
|
|
for k in keys:
|
|
debug(k, s)
|