58 lines
2.5 KiB
Python
Executable File
58 lines
2.5 KiB
Python
Executable File
"""Pengumpulan berita dari Google News RSS (feedparser).
|
|
Satu request per (kata kunci, jendela waktu) karena RSS membatasi jumlah item per request."""
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from datetime import date
|
|
from urllib.parse import urlencode
|
|
|
|
import feedparser
|
|
|
|
from ingestion.common import (KNOWN_MEDIA, build_record, host_of, media_from_url,
|
|
month_windows, parse_date_any, strip_html)
|
|
|
|
CHANNEL = "google_news"
|
|
BASE = "https://news.google.com/rss/search"
|
|
|
|
|
|
def _media_name(entry) -> str:
|
|
src = entry.get("source") or {}
|
|
href, title = src.get("href", ""), src.get("title", "")
|
|
if href and any(host_of(href).endswith(d) for d in KNOWN_MEDIA):
|
|
return media_from_url(href)
|
|
return title or (media_from_url(href) if href else "Google News")
|
|
|
|
|
|
def collect(keywords, start: date, end: date, session, window_days: int = 7, sleep: float = 1.5, limit: int | None = None):
|
|
n = 0
|
|
for a, b in month_windows(start, end, window_days):
|
|
for kw in keywords:
|
|
q = f"{kw} after:{a.isoformat()} before:{b.isoformat()}"
|
|
url = BASE + "?" + urlencode({"q": q, "hl": "id", "gl": "ID", "ceid": "ID:id"})
|
|
try:
|
|
resp = session.get(url, timeout=30)
|
|
resp.raise_for_status()
|
|
except Exception as exc: # jaringan/rate limit: lanjut ke jendela berikutnya
|
|
print(f"[google_news] gagal {a}..{b} '{kw}': {exc}")
|
|
time.sleep(sleep * 2)
|
|
continue
|
|
feed = feedparser.parse(resp.content)
|
|
for e in feed.entries:
|
|
media = _media_name(e)
|
|
title = (e.get("title") or "").strip()
|
|
raw_src = ((e.get("source") or {}).get("title") or "").strip()
|
|
for suffix in {raw_src, media}: # judul Google berformat "Judul - Nama Media"
|
|
if suffix and title.endswith(" - " + suffix):
|
|
title = title[: -len(suffix) - 3].strip()
|
|
break
|
|
summary = strip_html(e.get("summary"))
|
|
isi = "" if (not summary or summary.startswith(title[:40])) else summary
|
|
yield build_record(
|
|
judul=title, url=e.get("link", ""), tanggal=parse_date_any(e.get("published")),
|
|
sumber=media, sumber_data=CHANNEL, kata_kunci=kw, isi=isi,
|
|
)
|
|
n += 1
|
|
if limit and n >= limit:
|
|
return
|
|
time.sleep(sleep)
|