gpt4 book ai didi

python - Python 中的 URL 错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:31 24 4
gpt4 key购买 nike

我试图了解是否可以处理 python 中的以下错误。

所以我有一个程序重复调用以下行:

candidate = urllib2.urlopen(absolute_path)

运行程序几秒钟后,我关闭了 wifi 连接,并收到以下错误:

File "crawler.py", line 28, in urlQuery
candidate = urllib2.urlopen(absolute_path)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1214, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1184, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 65] No route to host>

有什么办法可以处理这个错误吗?

最佳答案

取决于您收到此异常时想要执行的操作。您可以使用标准 Python 的异常处理技术 try-except

try:
candidate = urllib2.urlopen(absolute_path)
#except Exception as e: # catches any exception
except urllib2.URLError as e: # catches urllib2.URLError in e
print ('WiFi connection perhaps lost !! Trying one more time...')
try:
candidate = urllib2.urlopen(absolute_path)
except:
print ('WiFi connection really lost !! Bailing out..')
print (e) # print outs the exception message

关于python - Python 中的 URL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26062054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com