0

I have a REST KML service that I am trying to import into a PostgreSQL table using Python 3. I haven't ever dealt directly with a KML service before, only JSON, and I'm having some trouble finding a way to consume this format. With JSON I use the response library similar to this:

import requests
import responses
response = requests.get('http://url_or_ip')
data = response.json()

I can then iterate through the data variable and get what I need, but I haven't found anything similar for KML. Is there a similar method to iterate through KML?

For reference, the service I'm trying to consume is located here: http://206.74.144.42/eitms/roadconditions/

Vince
  • 20,017
  • 15
  • 45
  • 64
Matt
  • 1,191
  • 1
  • 11
  • 25
  • 1
    I would simply download the KML file using requests and then I would import it to Postgres using ogr2ogr which can be called from Python. Check this answer for an example of using ogr2ogr to import a KML into a Postgres database. – Marcelo Villa Jul 29 '19 at 19:51
  • How frequently is the service updated? If you can get away with polling it periodically, you could use something like the simplekml library to get the geometries into WKT and use some regex or whatever to pull needed attributes from the description snippet. – auslander Jul 29 '19 at 21:10
  • 1
    data = str(response.content) gets you in your case the kml file as a string. from there on you could use pykml to access the data – zwnk Jul 30 '19 at 18:14

1 Answers1

0

Check out PyKML, as it has some good KML parsing capabilities for Python:

https://pythonhosted.org/pykml/

https://pythonhosted.org/pykml/tutorial.html#parsing-existing-kml-documents

Note that the KML source you linked to appears to not have the correct MIME type set on the server, since it's coming through as an XML page in my browser, instead of a KML file download.

Also, the data associated with each Point and LineString feature is in a blob of HTML in the description tag, so they will be a bit trickier to parse out as attributes, than if they were stored as ExtendedData name/value pairs in the KML itself.

Christiaan Adams
  • 2,918
  • 8
  • 18