51 lines
1.9 KiB
Python
51 lines
1.9 KiB
Python
#!/usr/bin/env python3
|
|
import requests
|
|
import argparse
|
|
import json
|
|
from bs4 import BeautifulSoup
|
|
|
|
def extract_json_from_html(html, script_id):
|
|
"""
|
|
Sucht in dem HTML nach dem Script-Tag mit der angegebenen ID
|
|
und gibt die darin enthaltene JSON-Struktur als Python-Daten zurück.
|
|
"""
|
|
soup = BeautifulSoup(html, "html.parser")
|
|
script = soup.find("script", id=script_id, type="application/json")
|
|
if script is None:
|
|
raise ValueError(f"Kein passendes Script-Tag mit ID '{script_id}' gefunden!")
|
|
json_str = script.string
|
|
data = json.loads(json_str)
|
|
return data
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Extrahiert JSON aus einem Script-Block einer Webseite und speichert es in einer Datei."
|
|
)
|
|
parser.add_argument("--url", default="https://www.humblebundle.com/bundles",
|
|
help="URL der Seite (Standard: https://www.humblebundle.com/bundles)")
|
|
parser.add_argument("--script-id", default="landingPage-json-data",
|
|
help="ID des Script-Tags, das das JSON enthält (Standard: landingPage-json-data)")
|
|
parser.add_argument("-o", "--output", default="extracted.json",
|
|
help="Ausgabedatei für das extrahierte JSON (Standard: extracted.json)")
|
|
args = parser.parse_args()
|
|
|
|
# HTTP-Request an die URL
|
|
response = requests.get(args.url)
|
|
if response.status_code != 200:
|
|
print(f"Fehler beim Laden der URL {args.url} (Status-Code: {response.status_code}).")
|
|
return
|
|
|
|
try:
|
|
data = extract_json_from_html(response.text, args.script_id)
|
|
except Exception as e:
|
|
print("Fehler beim Extrahieren des JSON:", e)
|
|
return
|
|
|
|
# JSON in eine Datei schreiben
|
|
with open(args.output, "w", encoding="utf-8") as f:
|
|
json.dump(data, f, indent=2, ensure_ascii=False)
|
|
print(f"JSON erfolgreich extrahiert und in '{args.output}' gespeichert.")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|