Python AttributeError: 'NoneType' 对象没有属性 'split'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/25882670/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:47:00  来源:igfitidea点击:
AttributeError: 'NoneType' object has no attribute 'split'
提问by MLSC
I have a script with these two functions:
我有一个具有这两个功能的脚本:
# 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
When I run program I have the following error:
当我运行程序时,出现以下错误:
result.append(cite.string.split('/')[0])
AttributeError: 'NoneType' object has no attribute 'split'
Output Sample:
输出样本:
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'
采纳答案by user1767754
It can happen, that the string has nothing inside, than it is "None" type, so what I can suppose is to check first if your string is not "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
回答by cppcoder
for cite in soup.find_all('cite'):
    if( (cite.string is None) or (len(cite.string) == 0)):
        continue
    result.append(cite.string.split('/')[0])

