使用Google的findplacefromtext-InvalidURL

时间:2019-11-15 10:58:42

标签: python google-maps google-api urllib street-address

我正在尝试使用Google API的findplacefromtext获取地址的详细信息。这是我的代码的样子:

def get_google_address(address):
    API_KEY = 'MY_API_KEY'
    URL = ('https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input={add}&inputtype=textquery&fields=formatted_address,name,geometry&key={API_KEY}').format(add=address,API_KEY=API_KEY)
    print(URL)
    response = urllib.request.urlopen(URL)
    data = json.load(response)
    return (data)

如果我按如下所示调用函数:get_google_address('1600 amphitheatre pkwy mountain view ca'),则会收到此错误:

InvalidURL: URL can't contain control characters. '/maps/api/place/findplacefromtext/json?input=1600 amphitheatre pkwy mountain view ca&inputtype=textquery&fields=formatted_address,name,geometry&key=API_KEY' (found at least ' ')

但是,如果我将URL粘贴到浏览器中,它将起作用。请让我知道我想念的东西。网址是这样的:https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=1600 amphitheatre pkwy mountain view ca&inputtype=textquery&fields=formatted_address,name,geometry&key=API_KEY

1 个答案:

答案 0 :(得分:0)

根据@geocodezip的评论,需要对URL进行编码:

dict1 = {'input':address, 'key':API_KEY}
qstr = urllib.parse.urlencode(dict1) 
URL = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?inputtype=textquery&fields=formatted_address,name,geometry&'
URL = URL + qstr
response = urllib.request.urlopen(URL)
data = json.load(response)
return (data)