8
我想趕上套接字超時(最好是一個例外)... except urllib.error.URLError:
可以捕獲它,但我需要區分死鏈接和超時....如果我拿出except urllib.error.URLError:
套接字超時沒有趕上和腳本在socket.timeout錯誤Catch套接字超時異常
import urllib.request,urllib.parse,urllib.error
import socket
import http
socket.setdefaulttimeout(0.1)
try:
file2 = urllib.request.Request('http://uk.geforce.com/html://')
file2.add_header("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.29 Safari/525.13")
file3 = urllib.request.urlopen(file2).read().decode("utf8", 'ignore')
except urllib.error.URLError: print('fail')
except socket.error: print('fail')
except socket.timeout: print('fail')
except UnicodeEncodeError: print('fail')
except http.client.BadStatusLine: print('fail')
except http.client.IncompleteRead: print('fail')
except urllib.error.HTTPError: print('fail')
print('done')
我才意識到你所標記的問題是Python的3.x的。不幸的是,我沒有訪問Python 3.上面的代碼應該適用於x> 3的2.x。 –