Python 中的 HTTP 请求和 JSON 解析 [英] HTTP requests and JSON parsing in Python

查看:44
本文介绍了Python 中的 HTTP 请求和 JSON 解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 Google Directions API 动态查询 Google Maps.例如,此请求计算了从伊利诺伊州芝加哥到加利福尼亚州洛杉矶经过乔普林 (密苏里州) 和俄克拉荷马城 (OK) 的两个航点的路线:

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:

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

它以 JSON 格式返回结果.

It returns a result in the JSON format.

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

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

推荐答案

我推荐使用很棒的 requests 库:

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

这篇关于Python 中的 HTTP 请求和 JSON 解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆