【问题标题】:Python - Continue not working in for loop?Python - 继续不在 for 循环中工作?
【发布时间】:2017-05-12 10:33:03
【问题描述】:

我正在使用 python 请求连接到一个网站,并且工作正常。

我的问题是我有一个我正在使用的代理列表,如果其中一个代理 ip 返回 404 错误,我需要我的 for 循环转到循环顶部并继续,直到我得到响应200 个。

当我的循环遇到异常/400-503 错误时,它不会返回到代码的顶部,而是直接离开循环,并继续执行代码。

快速说明: 代理数组有 6 个 ip,并且循环使它们都成为真。

怎么了,我使用下面的代码,继续?

for l in list:  
    for a in otherlist:
        for proxy in randomProxy:
            print 'Using Proxy: ', proxy
            try:
                r = requests.get(url, timeout=20, headers=headers, proxies=proxy)
                if r.status_code == 200:
                    response = r
                    print 'Good Proxy: ', proxy
                    pass
                else:
                    print 'Bad Proxy: ', proxy
                    continue
            except requests.exceptions.RequestException as e:
                # A serious problem happened, like an SSLError or InvalidURL
                print "Error: {}".format(e)
                continue

我真的不明白为什么会这样,也许我弄错了 continue 是如何工作的?

【问题讨论】:

    标签: python for-loop proxy python-requests


    【解决方案1】:

    这可能有效

    for proxy in randomProxy:
        print 'Using Proxy: ', proxy
        try:
            r = requests.get(url, timeout=20, headers=headers, proxies=proxy)
            if r.status_code == 200:
                response = r
                print 'Good Proxy: ', proxy
                break
            else:
                print('Bad Proxy:', proxy)
                print('Proxy is not working!')
                continue
        except:
             print('Bad Proxy:', proxy)
             print('Proxy is not working!')
    

    【讨论】:

    • 对不起@Amey 我在 stackoverflow 上有错误的缩进。 for 循环运行完美,但如果它遇到异常或 http 错误,那么我希望它继续使用列表中的下一个 ip。但它不会,你有什么好主意吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多