Python2.x到Python3.x的地理编码策略

2024-09-28 21:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取一些基本的googlemapsapi访问权限。在他们的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()

我将其转换为python3.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 \"results\" : [\n {\n \"address_components\" : [\n {\n \"long_name\" : \"1600\",\n
\"short_name\" : \"1600\",


Tags: httpsimportcomviewapijsonurladdress
1条回答
网友
1楼 · 发布于 2024-09-28 21:28:12

您遇到的问题是,获取二进制数据并用str将其包装成字符串。在Python3中,将二进制数据转换为字符串的正确方法是decode它。你知道吗

因此,在尝试将结果解释为json之前,应该将结果decode转换为字符串(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}}}]}

相关问题 更多 >