属性错误:'NoneType'对象没有'split'属性。

19

我有一个包含以下两个函数的脚本:

# Getting content of each page
def GetContent(url):
    response = requests.get(url)
    return response.content

# Extracting the sites
def CiteParser(content):
    soup = BeautifulSoup(content)
    print "---> site #: ",len(soup('cite'))
    result = []
    for cite in soup.find_all('cite'):
        result.append(cite.string.split('/')[0])
    return result

当我运行程序时,出现以下错误:

result.append(cite.string.split('/')[0])
AttributeError: 'NoneType' object has no attribute 'split'

输出样例:

URL: <URL That I use to search 'can be google, bing, etc'>
---> site #:  10
site1.com
.
.
.
site10.com

URL: <URL That I use to search 'can be google, bing, etc'>
File "python.py", line 49, in CiteParser
    result.append(cite.string.split('/')[0])
AttributeError: 'NoneType' object has no attribute 'split'

你能提供 content 参数的示例输入吗? - Bryan
2
cite.string 返回了一个 NoneType - cppcoder
@cppcoder 我怎么才能解决这个错误? - MLSC
在每次迭代中确保 cite.string 具有适当的值。在应用 split 函数之前进行验证。 - cppcoder
为了提供答案,你需要告诉我们什么是 cite 对象以及 cite.string 返回的内容是什么。 - cppcoder
cite是页面内容中类似于<cite></cite>的标签。它返回的是site1.com到site10.com - MLSC
2个回答

16

有时候字符串里面什么也没有,那么它就是“None”类型,所以我的建议是首先检查一下你的字符串是否不是“None”

# Extracting the sites
def CiteParser(content):
    soup = BeautifulSoup(content)
    #print soup
    print "---> site #: ",len(soup('cite'))
    result = []
    for cite in soup.find_all('cite'):
        if cite.string is not None:
            result.append(cite.string.split('/'))
            print cite
    return result

是的...我想这就是我所需要的...让我确认一下...谢谢。 - MLSC
6
检查 NoneType 类型时,最好使用isis not,而不是 ==!= - cppcoder
是的,我同意这一点,它不太符合Python的风格。 - user1767754

1
for cite in soup.find_all('cite'):
    if( (cite.string is None) or (len(cite.string) == 0)):
        continue
    result.append(cite.string.split('/')[0])

我也遇到了错误:TypeError: object of type 'NoneType' has no len()。我认为我应该删除 or (len(cite.string) == 0)) ... 是吗? - MLSC
1
你可以移除那个。但是长度检查被故意放在第二位,以便不检查 None 对象的长度。 - cppcoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接