【问题标题】:Geocoding Strategies - Python 2.x to Python 3.x地理编码策略 - Python 2.x 到 Python 3.x
【发布时间】:2015-09-02 04:13:23
【问题描述】:

我正在尝试获得对 Google Maps API 的一些基本访问权限。在他们的Geocoding Strategies 中,他们有一个示例展示了如何使用 Python 访问它:

import urllib2

address="1600+Amphitheatre+Parkway,+Mountain+View,+CA"
url="https://maps.googleapis.com/maps/api/geocode/json?address=%s" % address

response = urllib2.urlopen(url)
jsongeocode = response.read()

我将其转换为 python 3.4,但我获取的数据不是有效的 JSON 格式。另一种方法是使用 BeautifulSoup,但我不想做任何复杂的事情。

这是我在 Python 3.4 中使用的代码:

import urllib.request
import json

address="1600+Amphitheatre+Parkway,+Mountain+View,+CA"
url="https://maps.googleapis.com/maps/api/geocode/json?address=%s" % address

with urllib.request.urlopen(url) as link:
    s = str(link.read())

print(json.dumps(s))

这是我收到的数据的快照:

"b'{\n \"结果\" : [\n {\n \"address_components\" : [\n {\n \"long_name\" : \"1600\",\n
\"short_name\" : \"1600\",

【问题讨论】:

    标签: python json google-maps google-maps-api-3


    【解决方案1】:

    您遇到的问题是您正在获取二进制数据并通过使用str 将其包装成字符串。在 Python3 中将二进制数据转换为字符串的正确方法是 decode it。

    因此,您应该将结果decode 转换为字符串,然后再尝试将它们解释为 json(Python3.4 示例):

    with urllib.request.urlopen(url) as link:
        s = link.read()
        result = json.loads(s.decode('utf-8'))
    

    但我也建议您试一试requests,因为它可以为您简化这些步骤:

    >>> import requests
    >>> resp = requests.get(url)
    >>> resp.json()
    {'status': 'OK', 'results': [{'types': ['street_address'], 'place_id': 'ChIJ2eUgeAK6j4ARbn5u_wAGqWA', 'address_components': [{'types': ['street_number'], 'long_name': '1600', 'short_name': '1600'}, {'types': ['route'], 'long_name': 'Amphitheatre Parkway', 'short_name': 'Amphitheatre Pkwy'}, {'types': ['locality', 'political'], 'long_name': 'Mountain View', 'short_name': 'Mountain View'}, {'types': ['administrative_area_level_2', 'political'], 'long_name': 'Santa Clara County', 'short_name': 'Santa Clara County'}, {'types': ['administrative_area_level_1', 'political'], 'long_name': 'California', 'short_name': 'CA'}, {'types': ['country', 'political'], 'long_name': 'United States', 'short_name': 'US'}, {'types': ['postal_code'], 'long_name': '94043', 'short_name': '94043'}], 'formatted_address': '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA', 'geometry': {'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lat': 37.4236854802915, 'lng': -122.0828811197085}, 'southwest': {'lat': 37.4209875197085, 'lng': -122.0855790802915}}, 'location': {'lat': 37.4223365, 'lng': -122.0842301}}}]}
    

    【讨论】:

    • 字符串不应该在json的双引号中吗?另外,为什么'status': 'OK' 会出现在我的最后?
    • 1) 如果它是 Python 中有效的 json 字符串,那么 json 库将知道如何加载它。 Python 不区分单引号/双引号。它关心的规则(对于 json)是键/值是否有效以及是否正确形成。 2) 字典在 Python 中没有排序。没有理由在开始或结束时显示状态。
    • 感谢您的解释。工作得很好。
    猜你喜欢
    • 1970-01-01
    • 2013-10-17
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多