HTTP Requests and JSON Parsing in Python Using the Requests Library
If you wish to perform dynamic queries on Google Maps via the Google Directions API, the Python programming language provides an efficient solution. To initiate an HTTP request, receive the JSON response, and parse its contents, follow these steps:
Install the Requests Library: Begin by obtaining the Requests library using the following command:
pip install requests
Craft the Request: Formulate an HTTP GET request specifying the URL endpoint along with the desired request parameters:
url = 'http://maps.googleapis.com/maps/api/directions/json' params = { 'origin': 'Chicago,IL', 'destination': 'Los+Angeles,CA', 'waypoints': 'Joplin,MO|Oklahoma+City,OK', 'sensor': 'false' }
In this instance, the query is configured to retrieve the optimal route between Chicago and Los Angeles, incorporating two intermediary waypoints.
Send the Request: Dispatch the request by invoking the get() method of the Requests library, specifying the URL and parameters:
resp = requests.get(url=url, params=params)
Extract JSON Response: Retrieve the JSON content from the response object:
data = resp.json()
By embracing the Requests library, you gain a comprehensive toolkit for handling HTTP requests and parsing JSON responses in Python. This empowers you to seamlessly interact with various web services, such as Google Maps, and retrieve valuable information.
以上是如何使用 Python 和 Requests 函式庫查詢 Google Maps Directions API?的詳細內容。更多資訊請關注PHP中文網其他相關文章!