urllib
用于httplib
处理 HTTP 连接。如果您查看httplib.py
源代码并分析HTTPConnection
类,您将了解connect
方法的工作原理。
def connect(self):
"""Connect to the host and port specified in __init__."""
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
实际上,尝试次数取决于socket.getaddrinfo返回的列表的长度。该代码遍历所有可用的套接字选项来设置连接。
我怀疑减少尝试次数是否有意义。但是你可以像下面这样增加这个数字:
maxtries = 3
delay = 3
n = 0
while n < maxtries:
try:
resp = opener.open(url,None,1)
except e:
print ("no success")
n += 1
sleep(delay)
else:
print ("success!")
break