Git Product home page Git Product logo

schiene's Introduction

🚆 schiene

schiene is a Python library for interacting with Bahn.de. Consider it a unofficial API client. This library uses realtime, live information retrieved from Bahn.de and therefore contains information on delays, cancellations etc.

Note: if you do not need live information (delays etc.) you can use the new official Fahrplan API from Deutsche Bahn. Also, the Bahn.de HTML code is a steaming pile of shit that can cause this library to break at any time. Do not use for any critical stuff.

Install

pip install schiene

Usage examples

>>> import schiene
>>> s = schiene.Schiene()
>>> s.connections('Mannheim HbF', 'Stuttgart HbF')
[{'arrival': '13:08',
  'canceled': True,
  'delay' : {
    'delay_departure' : 15,
    'delay_arrival': 0
  }
  'departure': '12:30',
  'details': 'http://mobile.bahn.de/bin/mobil/query.exe/dox?ld=15085&n=1&i=or.0179785.1439546366&rt=1&use_realtime_filter=1&co=C0-1&vca&HWAI=CONNECTION$C0-1!details=opened!&',
  'price': 39.0,
  'products': ['ICE'],
  'time': '0:38',
  'transfers': 0},
 {'arrival': '13:54',
  'departure': '12:38',
  'details': 'http://mobile.bahn.de/bin/mobil/query.exe/dox?ld=15085&n=1&i=or.0179785.1439546366&rt=1&use_realtime_filter=1&co=C0-2&vca&HWAI=CONNECTION$C0-2!details=opened!&',
  'ontime': True,
  'price': 30.0,
  'products': ['S', 'EC'],
  'time': '1:16',
  'transfers': 1},
  ...]
>>> s.stations('Hamburg')
[{'extId': '008002549',
  'id': 'A=1@O=Hamburg '
        'Hbf@X=10006908@Y=53552732@U=80@L=008002549@B=1@p=1439332022@',
  'prodClass': '15',
  'state': 'id',
  'type': '1',
  'typeStr': '[Bhf/Hst]',
  'value': 'Hamburg Hbf',
  'weight': '24258',
  'xcoord': '10006908',
  'ycoord': '53552732'},
 {'extId': '008002548',
  'id': 'A=1@O=Hamburg '
        'Dammtor@X=9989568@Y=53560751@U=80@L=008002548@B=1@p=1439332022@',
  'prodClass': '31',
  'state': 'id',
  'type': '1',
  'typeStr': '[Bhf/Hst]',
  'value': 'Hamburg Dammtor',
  'weight': '27663',
  'xcoord': '9989568',
  'ycoord': '53560751'},
  ...]

Projects using schiene

Create a pull request to add your project here

schiene's People

Contributors

akloeckner avatar brice187 avatar fabaff avatar faserf avatar gpgmailencrypt avatar juliankahnert avatar kennell avatar kevvvvv avatar mkuhlmann avatar mweinelt avatar noxhirsch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

schiene's Issues

Better Alternative

I've used this API for one of my projects, but Marudor just made his HAFAS API online.
https://docs.marudor.de/#tag/HAFAS-V1
It has many more features and doesen't rely on some web scraping.
Just use some POST-Requests.

Parallel?

Hi there,

great package...it's really helpful.

Do you have any idea how I can do many requests at once?

thanks

Help with use

Hi,
I've got small question - I want to use this integration with HomeAssistant, but I have problems using it in Polish connections (Polish trains are visible on bahn.de).

I want to query for i.e. such connection:
https://reiseauskunft.bahn.de/bin/query.exe/dn?ld=43166&protocol=https:&seqnr=1&ident=i3.012020166.1659559405&rt=1&OK#hfsseq2|i3.012020166.1659559405
(starting point is Mysłowice and target is Katowice) and it works for "Myslowice"

I try to use it for "Mikołów" (Mikolow) and then there's no results at all, although there should be some:

https://reiseauskunft.bahn.de/bin/query.exe/dn?start=1&existOptimizePrice-deactivated=1&REQ0JourneyStopsS0A=1&S=Mikolow&REQ0JourneyStopsSID=A%3D1%40O%3DMikolow%40X%3D18899407%40Y%3D50172959%40U%3D80%40L%3D005102244%40B%3D1%40p%3D1659382252%40&REQ0JourneyStopsZ0A=1&Z=Katowice&REQ0JourneyStopsZID=A%3D1%40O%3DKatowice%40X%3D19017165%40Y%3D50257512%40U%3D80%40L%3D005100020%40B%3D1%40p%3D1659382252%40&date=Mi.%2C+03.08.2022&time=22%3A48&timesel=depart&returnDate=&returnTime=&optimize=0&auskunft_travelers_number=1&tariffTravellerType.1=E&tariffTravellerReductionClass.1=0&tariffClass=2&externRequest=yes&HWAI=JS%21js%3Dyes%21ajax%3Dyes%21#hfsseq1|kd.027210166.1659559734

I'm able to get data from:

import schiene
s = schiene.Schiene()
s.stations('Mikolow')

but not for

s.connections('Mikolow', 'Katowice')

Thanks for any help!

Schiene fails to convert price to float

File "/usr/local/lib/python3.4/site-packages/schiene/schiene.py", line 102, in connections
    return parse_connections(rsp.text)
  File "/usr/local/lib/python3.4/site-packages/schiene/schiene.py", line 33, in parse_connections
    data['price'] = float(data['price'])
ValueError: could not convert string to float: 'ab\xa02.70 EUR'

Hamburg-Eidelstedt not working

Not working:

>>> s.connections('Hamburg Burgwedel', 'Hamburg-Eidelstedt')
[]

Working:

>>> s.connections('Hamburg Burgwedel', 'Hamburg-Eidelstedt Zentrum')
[{'details': '...snipped..., 'canceled': False}]

"Hamburg-Eidelstedt" and "Hamburg-Eidelstedt Zentrum" are different stations and I want to have the first one as my target stations but it does not work. Is there something I can do? I am actually using homeassistent but I tried this explicitly in a python shell to pinpoint the issue.

Bahn declares cancelled train wrong?

Is there a limit to requests / seconds?

I am playing with this project and sometimes i get an empty list from the connections() function.

Is this due to requesting too often or due to some other error? Is there a specific limit?

Use pyhafas

Hello,

Use HAFAS instead off scraping. It should be more reliable and approved by Home Assistant as proper integration again.

https://github.com/FahrplanDatenGarten/pyhafas

I am happy to try and help to change it. Do you see any issue in using pyhafas?
I am now trying to add it into schiene. If you can give me any hints, I'd be very happy.

Requirement "lxml" missing

Hi, your setup.py seems to miss lxml as a required library (it is not automatically installed with BeautifulSoup4). Not a big deal, but you should probably add it (or use "html.parser", which afaik is always available).

Duration not accurate if >24 hours

If there are more than 24 hours between start and arrival the "time" value is not accurate. It does not take day changes into account.

Canceled connection is reported as 'ontime'

The Connection today from Stuttgart HBf to Ulm HBf at 10:51 was canceled (see. screenshot below), but connection is reported on time from schiene:

s.connections('Stuttgart HBf', 'Ulm HBf', datetime(2024, 4, 25, 10, 50, 0, 0))
[
{
"details": "https://mobile.bahn.de/bin/mobil/query.exe/dox?ld=4357&protocol=https:&n=1&i=dt.01855957.1714033988&rt=1&use_realtime_filter=1&co=C0-0&vca&HWAI=CONNECTION$C0-0!details=opened!detailsVerbund=opened!&",
"departure": "10:51",
"arrival": "11:34",
"transfers": 0,
"time": "0:43",
"products": ["ICE"],
"price": None,
"ontime": True,
"delay": {"delay_departure": 0, "delay_arrival": 0},
"canceled": False,
},
]

note: screenshot is taken from details-URL above, saved website is attached response.zip

image

Problem with Wolfbusch Station

python
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import schiene
s = schiene.Schiene()
s.connections('Wolfbusch, Stuttgart', 'Stuttgart-Feuerbach')

Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/schiene/schiene.py", line 135, in connections
return parse_connections(rsp.text)
File "/usr/local/lib/python2.7/dist-packages/schiene/schiene.py", line 35, in parse_connections
data = parse_delay(data)
File "/usr/local/lib/python2.7/dist-packages/schiene/schiene.py", line 65, in parse_delay
delay_arrival_raw = soup.find('div', class_="routeEnd").find('span', class_=["delay", "delayOnTime"])
AttributeError: 'NoneType' object has no attribute 'find'

"self.data.update & self.only_direct" in update

i use this package with home-assistant.

Since i upgraded i have following error:

"/usr/local/lib/python3.5/dist-packages/homeassistant/components/sensor/deutsche_bahn.py", line 82, in update
"/usr/local/lib/python3.5/dist-packages/homeassistant/components/sensor/deutsche_bahn.py", line 105, in update

Here is the same error reported what i had a couple times in log:

home-assistant/core#21118

self.data.update self.only_direct

Could you please fix it? :-)

Thanks a lot!

schiene crashes

Hi, the code crashes when trying to query the next train to Vienna. The 'Wien Hbf' is a valid name for the station as returned by s.stations('Wien')

s.connections('München','Wien Hbf')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "schiene.py", line 135, in connections
    return parse_connections(rsp.text)
  File "schiene.py", line 35, in parse_connections
    data = parse_delay(data)
  File "schiene.py", line 57, in parse_delay
    delay_departure_raw = soup.find('div', class_="routeStart").find('span', class_=["delay", "delayOnTime"])
AttributeError: 'NoneType' object has no attribute 'find'

>AttributeError: 'NoneType' object has no attribute 'find'< on certain connections

I tried using Schiene as a home assistant sensor but after the first try—it did work for a brief amount of time—, the underlying library stopped working.

The problematic connection for me has been from Leverkusen Mitte to Köln Hansaring

Home Assistant Log

deutsche_bahn: Error on device update!
Traceback (most recent call last):
  File "/usr/src/app/homeassistant/helpers/entity_component.py", line 397, in _async_add_entity
    yield from entity.async_device_update(warning=False)
  File "/usr/src/app/homeassistant/helpers/entity.py", line 308, in async_device_update
    yield from self.hass.async_add_job(self.update)
  File "/usr/local/lib/python3.6/asyncio/futures.py", line 327, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/local/lib/python3.6/asyncio/tasks.py", line 250, in _wakeup
    future.result()
  File "/usr/local/lib/python3.6/asyncio/futures.py", line 243, in result
    raise self._exception
  File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/app/homeassistant/components/sensor/deutsche_bahn.py", line 78, in update
    self.data.update()
  File "/usr/src/app/homeassistant/components/sensor/deutsche_bahn.py", line 99, in update
    self.start, self.goal, dt_util.as_local(dt_util.utcnow()))
  File "/usr/local/lib/python3.6/site-packages/schiene/schiene.py", line 135, in connections
    return parse_connections(rsp.text)
  File "/usr/local/lib/python3.6/site-packages/schiene/schiene.py", line 35, in parse_connections
    data = parse_delay(data)
  File "/usr/local/lib/python3.6/site-packages/schiene/schiene.py", line 57, in parse_delay
    delay_departure_raw = soup.find('div', class_="routeStart").find('span', class_="delay")
AttributeError: 'NoneType' object has no attribute 'find'

Command Line

I tried using Schiene directly using the command line but the same error arose.

>>> import schiene
>>> s = schiene.Schiene()
>>> s.connections('Leverkusen Mitte', 'Hansaring, Köln')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/schiene/schiene.py", line 135, in connections
    return parse_connections(rsp.text)
  File "/usr/local/lib/python3.6/site-packages/schiene/schiene.py", line 35, in parse_connections
    data = parse_delay(data)
  File "/usr/local/lib/python3.6/site-packages/schiene/schiene.py", line 57, in parse_delay
    delay_departure_raw = soup.find('div', class_="routeStart").find('span', class_="delay")
AttributeError: 'NoneType' object has no attribute 'find'

Not getting the next train correctly

Hey

I'm experimenting with your API and in general it is working. However when I make a

import schiene
data = schiene.Schiene()
res = data.connections('start', 'goal')

call, it returns a list of the next four trains for this connection. I think res[0] should be the next connection, however I usually see tat res[0] is the one after the next, and the next connecton is not
pulled in at all.

TypeError: unsupported operand type

I just started getting this error-message when trying get a connection.
Other destinations seem to work (e.g. 'Mannheim HbF' to 'Stuttgart HbF').
Is there anything I can check?

`$ python3
Python 3.7.3 (default, Oct 31 2022, 14:04:00)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

import schiene
s = schiene.Schiene()
s.connections('Wernau(neckar)', 'Wendlingen(neckar)')
Traceback (most recent call last):
File "", line 1, in
File "/home/dev/.local/lib/python3.7/site-packages/schiene/schiene.py", line 150, in connections
return parse_connections(rsp.text)
File "/home/dev/.local/lib/python3.7/site-packages/schiene/schiene.py", line 35, in parse_connections
data = parse_delay(data)
File "/home/dev/.local/lib/python3.7/site-packages/schiene/schiene.py", line 65, in parse_delay
delay_departure_raw.text)
File "/home/dev/.local/lib/python3.7/site-packages/schiene/schiene.py", line 106, in calculate_delay
diff = fullday - original + delayed
TypeError: unsupported operand type(s) for -: 'int' and 'datetime.datetime'`

"delay" not working

time: 0:55
arrival: 14:01
delay: 0
next_on: 13:29
ontime: false
icon: mdi:train
price: null
transfers: 1
products: RE,STR
friendly_name: Menden(Rheinl) to Bonn Gronau Olof-Palme-Allee
next: 13:29
departure: 13:06


As you can the the train is not ontime, but the delay is 0.
on the page www.bahn.de a delay of 20 minutes is shown.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.