如何摆脱一次尝试/除了在一段时间内?[Python]

2024-04-29 04:02:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试这个简单的代码,但是该死的中断不起作用。。。怎么了?

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'

它应该在连接工作时离开,如果没有,就回去尝试另一个代理

好吧,这就是我要做的

我试着去检查一个网站,如果它改变了,它必须在一段时间内中断才能继续脚本的其余部分,但是当代理没有连接时,我从变量中得到错误,因为它是空的,所以我想要的是work a s loop尝试一个代理,如果它成功了,继续脚本,然后脚本结束,返回并尝试下一个代理,如果下一个代理不起作用,则返回到开始时尝试第三个代理,依此类推。。。。

我在尝试这样的事情

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'

Tags: in脚本true代理forcheckcontenturllib
3条回答

您只会脱离for循环,因此永远不会离开while循环,并重新开始对proxylist进行一次又一次的迭代。只需省略周围的while循环,我实际上不理解为什么首先将代码封装在while True中。

你只是跳出了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'

您可以使用自定义异常,然后捕获它:

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'

相关问题 更多 >