Python中的HTTP请求和JSON解析

时间:2022-11-04 14:50:02

I want to dynamically query Google Maps through the Google Directions API. As an example, this request calculates the route from Chicago, IL to Los Angeles, CA via two waypoints in Joplin, MO and Oklahoma City, OK:

我想通过谷歌Directions API动态查询谷歌映射。例如,这个请求通过Joplin, MO和Oklahoma City的两个路径来计算从芝加哥到洛杉矶的路线,好:

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

http://maps.googleapis.com/maps/api/directions/json?origin=Chicago IL&destination =洛杉矶+洛杉矶,CA&waypoints =乔普林,莫|俄克拉荷马州+城市,OK&sensor = false

It returns a result in the JSON format.

它返回JSON格式的结果。

How can I do this in Python? I want to send such a request, receive the result and parse it.

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

6 个解决方案

#1


187  

I recommend using the awesome requests library:

我推荐使用超赞的请求库:

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 Response Content: http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content

JSON响应内容:http://docs.python-requests.org/en/latest/user/quickstart/ json-response-content

#2


104  

The requests Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the module's documentation:

请求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/...

So there is no use of having to use some separate module for decoding JSON.

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

#3


24  

requests has built-in .json() method

请求具有内置的.json()方法

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

#4


17  

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))

#5


12  

Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions.

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

#6


0  

Try this:

试试这个:

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))

#1


187  

I recommend using the awesome requests library:

我推荐使用超赞的请求库:

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 Response Content: http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content

JSON响应内容:http://docs.python-requests.org/en/latest/user/quickstart/ json-response-content

#2


104  

The requests Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the module's documentation:

请求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/...

So there is no use of having to use some separate module for decoding JSON.

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

#3


24  

requests has built-in .json() method

请求具有内置的.json()方法

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

#4


17  

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))

#5


12  

Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions.

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

#6


0  

Try this:

试试这个:

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))