1 | import requests
|
2 | import time
|
3 | from datetime import datetime
|
4 |
|
5 | def suche_stop(query):
|
6 | url = f"https://v6.db.transport.rest/locations?query={query}&results=5"
|
7 | try:
|
8 | resp = requests.get(url, timeout=10)
|
9 | if resp.status_code == 200:
|
10 | data = resp.json()
|
11 | print("Gefundene Stops:")
|
12 | for s in data:
|
13 | print(f"- ID: {s['id']}, Name: {s['name']}")
|
14 | return data[0]['id'] if data else None
|
15 | else:
|
16 | print(f"Suche-Fehler: {resp.status_code} - {resp.text}")
|
17 | except Exception as e:
|
18 | print(f"Netzwerkfehler: {e}")
|
19 | return None
|
20 |
|
21 | def verbindungen(from_id, to_id, results=5, when=None):
|
22 | url = "https://v6.db.transport.rest/journeys"
|
23 | params = {
|
24 | 'from': from_id,
|
25 | 'to': to_id,
|
26 | 'results': results,
|
27 | 'language': 'de'
|
28 | }
|
29 | if when:
|
30 | params['when'] = when # z.B. '2026-04-27T18:00'
|
31 | try:
|
32 | resp = requests.get(url, params=params, timeout=15)
|
33 | print(f"Status: {resp.status_code}")
|
34 | if resp.status_code == 200:
|
35 | data = resp.json()
|
36 | journeys = data.get('journeys', [])
|
37 | print(f"\n{len(journeys)} beste Verbindungen Stuttgart → München (Stand: {datetime.now().strftime('%H:%M')}):")
|
38 | for i, j in enumerate(journeys[:3], 1): # Erste 3
|
39 | duration = j.get('duration', 'N/A')
|
40 | legs_count = len(j.get('legs', []))
|
41 | first_leg = j['legs'][0]
|
42 | dep_time = first_leg['departure']
|
43 | print(f"\n{i}. Dauer: {duration}, {legs_count} Etappe(n)")
|
44 | print(f" Abfahrt: {dep_time} {first_leg.get('line', {}).get('name', 'Fußweg')}")
|
45 | print(f" Ziel: {j['legs'][-1]['arrival']} {j['legs'][-1].get('line', {}).get('name', '')}")
|
46 | elif resp.status_code == 500:
|
47 | print("Serverfehler (500): Retry in 60s...")
|
48 | time.sleep(60)
|
49 | return verbindungen(from_id, to_id, results)
|
50 | else:
|
51 | print(f"Fehler: {resp.status_code} - {resp.text[:300]}")
|
52 | except Exception as e:
|
53 | print(f"Ausnahme: {e}")
|
54 |
|
55 | if __name__ == "__main__":
|
56 | from_stop = suche_stop("Stuttgart Hbf")
|
57 | to_stop = suche_stop("München Hbf")
|
58 | if from_stop and to_stop:
|
59 | verbindungen(from_stop, to_stop)
|