HTTP-Anfragen und JSON-Parsing in Python

Ich möchte Google Maps dynamisch über die Google Directions API abfragen. Als Beispiel berechnet diese Anfrage die Route von Chicago, IL nach Los Angeles, CA über zwei Wegpunkte in Joplin, MO und Oklahoma City, OK:

http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false

Es wird ein Ergebnis im JSON-Format zurückgegeben.

Wie kann ich das in Python machen? Ich möchte eine solche Anfrage senden, das Ergebnis erhalten und es parsen.

Lösung

Ich empfehle die großartige requests-Bibliothek zu verwenden:

import requests

url = 'http://maps.googleapis.com/maps/api/directions/json'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)

resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below

JSON Antwort Inhalt: http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content

Kommentare (1)
import urllib
import json

url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
result = json.load(urllib.urlopen(url))
Kommentare (4)

Verwenden Sie die Anforderungsbibliothek, drucken Sie die Ergebnisse hübsch aus, damit Sie die Schlüssel/Werte, die Sie extrahieren möchten, besser lokalisieren können, und verwenden Sie dann verschachtelte for-Schleifen, um die Daten zu analysieren. In dem Beispiel extrahiere ich Schritt für Schritt Fahranweisungen.

import json, requests, pprint

url = 'http://maps.googleapis.com/maps/api/directions/json?'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)

data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)

# test to see if the request was valid
#print output['status']

# output all of the results
#pprint.pprint(output)

# step-by-step directions
for route in output['routes']:
        for leg in route['legs']:
            for step in leg['steps']:
                print step['html_instructions']
Kommentare (2)