AttributeError:“module”对象没有属性“ValueError”

2024-10-03 04:29:03 发布

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

所以我在使用tld库时遇到了一些问题,它不知道如何处理某些代理请求url。为了解决这个问题,添加了一些异常,它适用于特定日期的数据。在

import tld
from tld import get_fld

#Custom try-except function to handle IPs and garbage http requests
def try_get_fld(x):
    try: 
        return get_fld(x)
    except tld.exceptions.TldBadUrl: 
        return np.nan
    except tld.exceptions.TldDomainNotFound:
        return np.nan

#Apply the function above to the request dataframe
request['flds'] = request['request'].apply(try_get_fld)

但在另一天,我遇到了一个新的错误:

^{pr2}$

所以我在例外的基础上加上了:

def try_get_fld(x):
    try: 
        return get_fld(x)
    except tld.exceptions.TldBadUrl: 
        return np.nan
    except tld.exceptions.TldDomainNotFound:
        return np.nan
    except tld.exceptions.ValueError:
        return np.nan

然后我遇到了一个属性错误:

AttributeError: 'module' object has no attribute 'ValueError'

所以我在例外情况下加了一句:

def try_get_fld(x):
    try: 
        return get_fld(x)
    except tld.exceptions.TldBadUrl: 
        return np.nan
    except tld.exceptions.TldDomainNotFound:
        return np.nan
    except tld.exceptions.ValueError:
        return np.nan
    except tld.exceptions.AttributeError:
        return np.nan

然后我得到AttributeError:“module”对象又没有属性“ValueError”。在

有没有人知道我做错了什么或者如何解决我的问题?目标只是用NaN标记请求url,这样我就可以将该方法应用于我的数据集。在


Tags: getreturnrequestdefnpnanexceptionsattributeerror
2条回答

您可以指定异常列表,使代码简洁。在

def try_get_fld(x):
    try: 
        return get_fld(x)
    except (tld.exceptions.TldBadUrl, 
            tld.exceptions.TldDomainNotFound, 
            ValueError): 
        return np.nan

这是因为ValueError是一个Python内置异常,而不是{}的成员。使用except ValueError代替tld.exceptions.ValueError。在

相关问题 更多 >