【问题标题】:After recursion I got an Error (TypeError: 'NoneType' object is not iterable)递归后我得到一个错误(TypeError:'NoneType'对象不可迭代)
【发布时间】:2020-07-09 01:17:48
【问题描述】:

我正在尝试使用代理 request.get() 并使用 try/except。 如果我的代理错误,我使用except,更改代理并重新启动此功能。

递归后我得到了所有需要的值和

TypeError: 'NoneType' 对象不可迭代

我不知道为什么?

P.S.:如果代码在不调用 except 的情况下运行,它可以完美运行

def get_html_v2(url, proxy, userAgent):
    data = None
    status = None
    userAgent = userAgent or ''
    proxies = {
        "http": "http://"+proxy,
        "https":"http://"+proxy
    }
    try:
        # Get request
        response = requests.get(url=url, headers=userAgent, proxies=proxies)
        # Get a status of the request
        status = response.status_code
        # Return request values and status
        return response.text, int(status)
    # If proxy doesn't work
    except ConnectionError:
        # Remove wrong proxy from List
        proxiesList.remove(proxy)
        # Get new proxy
        proxy = random.choice(proxiesList)
        # Start function again
        get_html_v2(url, userAgent=userAgent, proxy=proxy)

【问题讨论】:

    标签: python python-requests typeerror nonetype


    【解决方案1】:

    不清楚错误发生在哪里,因为上面的代码不包含任何迭代。最好包括该错误部分。

    无论如何,错误可能是由于您的except 块中的get_html_v2 而发生的。您在 except 块中调用 get_html_v2() 但没有returning 导致调用者/上一个递归循环,无论如何你都必须这样做,尤其是递归。

    except 块的最后一行,替换:

     get_html_v2(url, userAgent=userAgent, proxy=proxy)
    

    与:

     return get_html_v2(url, userAgent=userAgent, proxy=proxy)
    

    这样,您实际上是在您的 try 块中返回从行 return response.text, int(status) 返回的值。

    P.S.:如果代码在不调用 except 的情况下运行,它可以完美运行

    except 块被调用时,由于没有return,它隐式返回None。当它没有被调用时,它会返回response.text, int(status)

    【讨论】:

    • Wrt “不清楚错误发生在哪里”:可能在处理try 块中返回的元组(response.text, int(status)) 时,因此您的代码期望所有返回值是一个元组,而不是None
    • 非常感谢!这行得通! return get_html_v2(url, userAgent=userAgent, proxy=proxy)
    猜你喜欢
    • 2021-12-16
    • 2012-03-26
    • 2012-08-25
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    相关资源
    最近更新 更多