我创建的字典不是我想要的输出,我不知道我的代码有什么问题。
代码如下:
hostInfoDict = {
'192.168.247.62': {80: 'http', 8080: 'http-proxy'},
'192.168.247.64': {80: 'http', 8080: 'http-proxy'},
'192.168.247.74': {80: 'http', 8080: 'http-proxy'}
}
for host, hostInfo in hostInfoDict.items():
httpHostStatusDict = {}
for port in hostInfo.keys():
urls = 'http://' + host + ":" + str(port) + '/thredds/catalog.html'
#print(urls)
try:
r = requests.get(urls, timeout=0.5, allow_redirects=False)
#print(urls, r.status_code)
except requests.exceptions.HTTPError:
"""An HTTP error occurred."""
pass
except requests.exceptions.ConnectionError:
"""A Connection error occurred."""
pass
except requests.exceptions.Timeout:
"""
The request timed out while trying to connect to the remote server.
Requests that produced this error are safe to retry.
"""
pass
except requests.exceptions.RequestException:
"""
There was an ambiguous exception that occurred while handling your request.
"""
pass
try:
if urls not in httpHostStatusDict:
httpHostStatusDict[urls] = str(r.status_code)
except:
pass
print(httpHostStatusDict)上述代码的输出如下所示。它们是分开的,而不是整个字典。
{'http://192.168.247.62:80/thredds/catalog.html': '200', 'http://192.168.247.62:8080/thredds/catalog.html': '200'}
{'http://192.168.247.64:80/thredds/catalog.html': '404', 'http://192.168.247.64:8080/thredds/catalog.html': '404'}
{'http://192.168.247.74:80/thredds/catalog.html': '200', 'http://192.168.247.74:8080/thredds/catalog.html': '200'}预期输出为
{
{'http://192.168.247.62:80/thredds/catalog.html': '200'},
{'http://192.168.247.62:8080/thredds/catalog.html': '200'},
{'http://192.168.247.64:80/thredds/catalog.html': '404'},
{'http://192.168.247.64:8080/thredds/catalog.html': '404'},
{'http://192.168.247.74:80/thredds/catalog.html': '200'},
{'http://192.168.247.74:8080/thredds/catalog.html': '200'}
}这是一个Python请求项目:)我认为这是一个代码问题,所以我不认为你需要安装库。你的帮助是我的谢意。
发布于 2018-08-22 10:13:50
您应该将httpHostStatusDict = {}放在第一个for循环之前,而print应该放在整个第一个for代码之后。
https://stackoverflow.com/questions/51958953
复制相似问题