我正在尝试这个简单的代码,但该死的休息不起作用......出了什么问题?
while True:
for proxy in proxylist:
try:
h = urllib.urlopen(website, proxies = {'http': proxy}).readlines()
print 'worked %s' % proxy
break
except:
print 'error %s' % proxy
print 'done'
当连接工作时,它应该离开,并返回并尝试另一个代理,如果它没有
好的,这就是我正在做的事情我正在尝试检查一个网站,如果它发生了变化,它必须突破一段时间才能继续执行其余的脚本,但是当代理没有连接时,我从变量中得到错误,如它是null,所以我想要的是作为循环来尝试代理,如果它工作,继续脚本,脚本的结束,返回并尝试下一个代理,如果下一个不起作用,它将回到开始尝试第三个代理,依此类推......
我正在尝试这样的事情
while True:
for proxy in proxylist:
try:
h = urllib.urlopen(website, proxies = {'http': proxy})
except:
print 'error'
check_content = h.readlines()
h.close()
if check_before != '' and check_before != check_content:
break
check_before = check_content
print 'everything the same'
print 'changed'
答案 0 :(得分:11)
你刚刚摆脱for
循环 - 而不是while
循环:
running = True
while running:
for proxy in proxylist:
try:
h = urllib.urlopen(website, proxies = {'http': proxy}).readlines()
print 'worked %s' % proxy
running = False
except:
print 'error %s' % proxy
print 'done'
答案 1 :(得分:4)
您可以使用自定义异常然后捕获它:
exit_condition = False
try:
<some code ...>
if exit_conditon is True:
raise UnboundLocalError('My exit condition was met. Leaving try block')
<some code ...>
except UnboundLocalError, e:
print 'Here I got out of try with message %s' % e.message
pass
except Exception, e:
print 'Here is my initial exception'
finally:
print 'Here I do finally only if I want to'
答案 2 :(得分:3)
您只会突破for
循环,因此您永远不会离开while循环并重新开始遍历proxylist
一遍又一遍。只是省略周围的while循环,我实际上不明白为什么你首先将代码包含在while True
中。
答案 3 :(得分:1)
break打破了最里面的循环,这是你的情况下的for
循环。要从多个循环中断,您几乎没有选择:
return
但在你的情况下,你实际上根本不需要外部while
循环。只需删除它。