使用 Google 的 findplacefromtext 时出错 - InvalidURL

Error while using Google's findplacefromtext - InvalidURL

我正在尝试使用 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 粘贴到浏览器中,它就会起作用。请让我知道我错过了什么。 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

根据@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)