urlib错误:“urllib.error.URLError:<urlopen error no host given>“

2024-04-16 23:12:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

Tags: keyhttpsjsonresponserequest错误教程origin
3条回答

我认为您应该使用^{}库,但您的问题似乎在于字符串格式。例如:

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

'London'中没有空格可替换为+'('Heathrow').replace(' ', '+')'也一样。然后在nav_request = 'origin={} &destination={} &key={}'中引入空格,但为时已晚。London'.replace(' ', '+')仍然是{}。在

可能是以下几点:

^{pr2}$

有几件事:

“https:”后面有三个斜杠。这是访问文件(即文件:///废话.txt),但对HTTP无效。虽然浏览器可以纠正这一点,但它不能处理urllib或请求。在

2-你用你定义navrequest的方式有未被占用的空间。我建议您对构建的navrequest进行替换,而不是对每个组件进行替换,这样只需执行一次(也更易于阅读)。在

如其他人所说,我建议使用requests模块(或者grequests,如果您想异步操作的话)。在

您的URL没有主机名。Scheme、冒号、两个斜杠、主机名、斜杠、路径、可选问号和查询字符串、可选哈希和片段。你有三个连续的斜杠。在

相关问题 更多 >