我正在尝试获取一些基本的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\",
您遇到的问题是,获取二进制数据并用
str
将其包装成字符串。在Python3中,将二进制数据转换为字符串的正确方法是decode
它。你知道吗因此,在尝试将结果解释为json之前,应该将结果
decode
转换为字符串(Python3.4示例):但我也建议给requests一次机会,因为这样可以简化这些步骤:
相关问题 更多 >
编程相关推荐