使用Google的findplacefromtext时出错-InvalidURL

问题描述 投票:-1回答:1

我正在尝试使用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

python google-maps google-api urllib street-address
1个回答
0
投票

基于@geocodezip的注释,需要对URL进行编码:

mydict = {'input':address, 'key':API_KEY}
qstr = urllib.parse.urlencode(mydict) 
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)
© www.soinside.com 2019 - 2024. All rights reserved.