Python中的HTTP请求和JSON解析

我想通过Google Directions API动态地查询Google Maps。作为一个例子,这个请求计算了从伊利诺伊州的芝加哥到加利福尼亚州的路线,途径密苏里州的乔普林和俄克拉荷马城的两个航点。

http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&目的地=Los+Angeles,CA&航点=Joplin,MO|Oklahoma+City,OK&传感器=false

它返回一个结果以JSON格式

我怎样才能在Python中做到这一点?我想发送这样一个请求,接收结果并解析它。

解决办法

我推荐使用令人敬畏的request库。

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响应内容。http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content

评论(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))
评论(4)

使用请求库,漂亮地打印结果,这样你可以更好地定位你想提取的键/值,然后使用嵌套for循环来解析数据。在这个例子中,我提取了一步步的驾驶指南。

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']
评论(2)