Python中的HTTP请求和JSON解析

我想通过谷歌方向API动态查询谷歌地图。例如,这个请求计算了从伊利诺伊州芝加哥到加利福尼亚州洛杉矶的路线,途经密苏里州乔普林和俄克拉荷马城的两个路点,OK:

http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|俄克拉荷马+城市,OK&sensor=false

它返回一个结果JSON格式

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

861484 次浏览
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))

我建议使用很棒的请求库:

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响应内容:https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content

使用请求库,漂亮地打印结果,以便更好地定位想要提取的键/值,然后使用嵌套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']

requests Python模块由于其内置的JSON解码器,负责检索JSON数据和解码数据。下面是一个来自模块的文档的例子:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

因此,没有必要使用一些单独的模块来解码JSON。

requests有内置的.json()方法

import requests
requests.get(url).json()

试试这个:

import requests
import json


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


# Request data from link as 'str'
data = requests.get(link).text


# convert 'str' to Json
data = json.loads(data)


# Now you can access Json
for i in data['routes'][0]['legs'][0]['steps']:
lattitude = i['start_location']['lat']
longitude = i['start_location']['lng']
print('{}, {}'.format(lattitude, longitude))

对于控制台的漂亮Json:

 json.dumps(response.json(), indent=2)

可以使用缩进转储。(请进口json)

只是import requests和使用from json()方法:

source = requests.get("url").json()
print(source)

或者你可以用这个:

import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)