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/

3
  • 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. Commented Jul 29, 2019 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
    Commented Jul 29, 2019 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
    Commented Jul 30, 2019 at 18:14

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.