183 lines
6.7 KiB
Python
183 lines
6.7 KiB
Python
import requests
|
|
import re
|
|
import json
|
|
from bs4 import BeautifulSoup
|
|
from datetime import datetime
|
|
|
|
BEEPWORLD_URL = "http://genialdaneben.beepworld.de/2008.htm"
|
|
WIKI_API_URL = "https://de.wikipedia.org/w/api.php"
|
|
WIKI_PAGE_TITLE = "Genial daneben/Episodenliste"
|
|
|
|
USER_AGENT = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"}
|
|
|
|
# Standard-Panel (Wird pro Folge um Gäste ergänzt)
|
|
PANEL_STANDARD = ["Hella von Sinnen", "Bernhard Hoëcker"]
|
|
|
|
# =========================================
|
|
# HELFER: DATUM & WIKIPEDIA
|
|
# =========================================
|
|
|
|
def normalize_date(raw_date):
|
|
months = {"Januar":1,"Februar":2,"März":3,"April":4,"Mai":5,"Juni":6,"Juli":7,"August":8,"September":9,"Oktober":10,"November":11,"Dezember":12}
|
|
# Format: 10.Mai, 2008
|
|
match = re.search(r"(\d{1,2})\.([A-Za-zäöüÄÖÜ]+),?\s*(\d{4})", raw_date)
|
|
if match:
|
|
day, m_name, year = match.groups()
|
|
month = months.get(m_name.capitalize())
|
|
if month: return f"{year}-{month:02d}-{int(day):02d}"
|
|
# Format: 10.05.2008
|
|
match_std = re.search(r"(\d{1,2})\.(\d{1,2})\.(\d{2,4})", raw_date)
|
|
if match_std:
|
|
day, month, year = match_std.groups()
|
|
if len(year) == 2: year = "20" + year
|
|
return f"{year}-{int(month):02d}-{int(day):02d}"
|
|
return None
|
|
|
|
def fetch_wikipedia_raw():
|
|
params = {"action": "query", "prop": "revisions", "rvprop": "content", "format": "json", "titles": WIKI_PAGE_TITLE}
|
|
r = requests.get(WIKI_API_URL, params=params, headers=USER_AGENT)
|
|
data = r.json()
|
|
page = next(iter(data["query"]["pages"].values()))
|
|
return page.get("revisions",[{}])[0].get("*","")
|
|
|
|
def find_episode_number(wiki_raw, date_iso):
|
|
if not date_iso: return None
|
|
y, m, d = date_iso.split("-")
|
|
day_short = str(int(d))
|
|
month_short = str(int(m))
|
|
|
|
# Suchmuster für Wikipedia (z.B. | 324 | 10.05.2008 oder | 324 | 10. 5. 2008)
|
|
patterns = [
|
|
rf"\|\s*(\d+)\s*\|.*?{day_short}\.\s*{month_short}\.\s*{y}",
|
|
rf"\|\s*(\d+)\s*\|.*?{d}\.{m}\.{y}"
|
|
]
|
|
for pat in patterns:
|
|
match = re.search(pat, wiki_raw)
|
|
if match: return int(match.group(1))
|
|
return None
|
|
|
|
# =========================================
|
|
# HELFER: LÖSER-EXTRAKTION & REINIGUNG
|
|
# =========================================
|
|
|
|
def extract_loeser(text_segment, panel):
|
|
"""
|
|
Prüft ob die Antwort mit 'j' beginnt und ordnet Namen zu.
|
|
"""
|
|
clean_segment = text_segment.strip().lower()
|
|
|
|
# Wenn die Antwort nicht mit 'j' (gelöst) beginnt, leere Liste
|
|
if not clean_segment.startswith('j'):
|
|
return []
|
|
|
|
if "team" in clean_segment:
|
|
return panel
|
|
|
|
gefundene = []
|
|
for person in panel:
|
|
# Wir suchen nach dem Nachnamen im Header der Antwort
|
|
nachname = person.split()[-1].lower()
|
|
if nachname in clean_segment:
|
|
if person not in gefundene:
|
|
gefundene.append(person)
|
|
|
|
return gefundene
|
|
|
|
def clean_answer_text(text, panel):
|
|
"""
|
|
Entfernt j/n, Bindestriche und Namen restlos vom Textanfang.
|
|
"""
|
|
# 1. j/n und Striche/Doppelpunkte weg
|
|
text = re.sub(r'^[jnyJNY]\s*[:\-–—]?\s*', '', text)
|
|
# 2. Team-Marker weg
|
|
text = re.sub(r'^team\s*[:\-–—]?\s*', '', text, flags=re.IGNORECASE)
|
|
# 3. Panel-Nachnamen am Anfang weg
|
|
for person in panel:
|
|
nachname = person.split()[-1]
|
|
text = re.sub(r'^' + re.escape(nachname) + r'[\s,:\-–—]*', '', text, flags=re.IGNORECASE)
|
|
return text.strip()
|
|
|
|
# =========================================
|
|
# SCRAPER CORE
|
|
# =========================================
|
|
|
|
def scrape():
|
|
html = requests.get(BEEPWORLD_URL).text
|
|
soup = BeautifulSoup(html, "html.parser")
|
|
text = soup.get_text("\n")
|
|
wiki_raw = fetch_wikipedia_raw()
|
|
|
|
lines = [l.strip() for l in text.splitlines() if l.strip()]
|
|
|
|
episodes = []
|
|
current_ep = None
|
|
current_q = None
|
|
|
|
for line in lines:
|
|
# 1. Datumserkennung (Der Episoden-Anker)
|
|
date_iso = normalize_date(line)
|
|
if date_iso:
|
|
if current_ep: episodes.append(current_ep)
|
|
current_ep = {
|
|
"folge_nummer": find_episode_number(wiki_raw, date_iso),
|
|
"datum": date_iso,
|
|
"panel": PANEL_STANDARD.copy(),
|
|
"fragen": []
|
|
}
|
|
continue
|
|
|
|
if not current_ep: continue
|
|
|
|
# 2. Panel-Ergänzung (Gäste finden)
|
|
if "(mit:" in line or "Gäste:" in line:
|
|
match = re.search(r"(?:\(mit:|Gäste:)\s*(.*)\)?", line)
|
|
if match:
|
|
guests = [n.strip() for n in re.split(r",| und ", match.group(1).replace(')',''))]
|
|
for g in guests:
|
|
if g and g not in current_ep["panel"]:
|
|
current_ep["panel"].append(g)
|
|
continue
|
|
|
|
# 3. Fragen erkennen
|
|
if line.startswith(("Frage:", "ZFrage:")):
|
|
q_text = line.split(":", 1)[1].strip()
|
|
current_q = {"frage": q_text, "antwort": "", "geloest_durch": []}
|
|
current_ep["fragen"].append(current_q)
|
|
current_state = "FRAGE" # Wir sammeln jetzt Text für die Frage
|
|
continue
|
|
|
|
# 4. Antworten erkennen
|
|
if line.startswith("Antwort:") and current_q:
|
|
raw_a_content = line.split(":", 1)[1].strip()
|
|
current_q["geloest_durch"] = extract_loeser(raw_a_content, current_ep["panel"])
|
|
current_q["antwort"] = clean_answer_text(raw_a_content, current_ep["panel"])
|
|
current_state = "ANTWORT" # Ab jetzt gehört Folgetext zur Antwort
|
|
continue
|
|
|
|
# 5. Multiline-Inhalte (Fortsetzungen)
|
|
if current_q:
|
|
if current_state == "FRAGE":
|
|
current_q["frage"] = (current_q["frage"] + " " + line).strip()
|
|
elif current_state == "ANTWORT":
|
|
current_q["antwort"] = (current_q["antwort"] + " " + line).strip()
|
|
|
|
if current_ep: episodes.append(current_ep)
|
|
return episodes
|
|
|
|
if __name__ == "__main__":
|
|
data = scrape()
|
|
with open("genial_daneben_2008_archiv.json", "w", encoding="utf-8") as f:
|
|
json.dump(data, f, ensure_ascii=False, indent=4)
|
|
|
|
print(f"Fertig! {len(data)} Episoden in 'genial_daneben_2008_archiv.json' gespeichert.")
|
|
|
|
# Kleiner Check-Output für die Konsole
|
|
if data:
|
|
test_ep = data[0]
|
|
print(f"\nTest-Check (Erste Folge):")
|
|
print(f"Folge: {test_ep['folge_nummer']} vom {test_ep['datum']}")
|
|
print(f"Panel: {', '.join(test_ep['panel'])}")
|
|
for i, q in enumerate(test_ep['fragen'][:2], 1):
|
|
print(f" Q{i}: {q['frage'][:50]}...")
|
|
print(f" A{i}: {q['antwort'][:50]}...")
|
|
print(f" Löser: {q['geloest_durch']}") |