python - 属性错误 : 'NoneType' object has no attribute 'split'

标签 python attributes split

我有一个具有这两个功能的脚本:

# 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'

最佳答案

可能会发生,字符串内部没有任何内容,而不是“无”类型,所以我可以假设首先检查您的字符串是否不是“无”

# 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

关于python - 属性错误 : 'NoneType' object has no attribute 'split' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25882670/

相关文章:

Java - 分割字符串以获取十进制数

java - 从字符串数组+颜色词中获取每个单词

python - peewee:对象没有属性 _meta

Jquery-如何获取样式显示属性 "none/block"

c# - 为什么 "decimal"不是有效的属性参数类型?

xsd - 在 XSD 中的许多元素上重用属性

java - 对空格、 "("和 ")"进行字符串 split()

python - 为什么这些语句不返回 'true' ?

python - 基于点创建平滑线

python - 并行运行子进程