乌利布错误:"urllib.error.URLError: <urlopen error no host given>"



我遇到了这个错误,按行复制教程。在这里是:

endpoint = 'https:///maps.googleapi.com/maps/api/directions/json?'
origin = ('London').replace(' ', '+')
destination = ('Heathrow').replace(' ', '+')
nav_request = 'origin={} &destination={} &key={}' .format(origin,destination,googleDir_key)
request = endpoint + nav_request
response = urllib.request.urlopen(request).read()
directions = json.loads(response)
print(directions)

您的URL没有主机名。方案,结肠,两个斜线,主机名,斜线,路径,可选问号和查询字符串,可选哈希和片段。您连续三个斜线。

我认为您可能应该使用requests库,但是您的问题似乎在字符串格式中。例如:

origin = ('London').replace(' ', '+')

'London'中没有+代替的空格。'('Heathrow').replace(' ', '+')'也是如此。然后,您在nav_request = 'origin={} &destination={} &key={}'中介绍Whitespace,但为时已晚。London'.replace(' ', '+')仍将是'origin=London '

也许以下内容:

nav_request = 'origin={}+&destination={}+&key={}'.format(origin,destination,googleDir_key)

几件事:

1-您在'https:'之后有三个斜杠。这就是您访问文件(即文件:///blah.txt(的方式,但是它对HTTP无效。虽然浏览器会纠正此问题,但它无法与Urllib或请求一起使用。

2-您的定义navrequest的方式没有示例空间。我建议您在构建的navrequest上而不是每个组件上进行替换

ps-正如其他人所说的,我建议使用"请求"模块(如果您想异步操作,请使用grequest(。

因为您将额外的/之后放置了https之后,因此Urllib无法检测到主机名。在您的情况下,请考虑以下代码示例:

from urllib.parse import urlparse
endpoint = 'https:///maps.googleapi.com/maps/api/directions/json'
endpoint = urlparse(endpoint)
print(endpoint.netloc)
print(endpoint)

输出将是:

''
ParseResult(scheme='https', netloc='', path='/maps.googleapi.com/maps/api/directions/json', params='', query='', fragment='')

现在删除额外/https之后:您的端点变量将被修改。现在再次运行上一个代码:

from urllib.parse import urlparse
endpoint = 'https://maps.googleapi.com/maps/api/directions/json'
endpoint = urlparse(endpoint)
print(endpoint.netloc)
print(endpoint)

输出将是:

maps.googleapi.com
ParseResult(scheme='https', netloc='maps.googleapi.com', path='/maps/api/directions/json', params='', query='', fragment='')

现在您看到差异

相关内容

最新更新