AttributeError: 'NoneType' オブジェクトに属性 'split' がありません 質問する

AttributeError: 'NoneType' オブジェクトに属性 'split' がありません 質問する

次の 2 つの関数を含むスクリプトがあります。

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

ベストアンサー1

文字列に何も含まれていない場合は「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

おすすめ記事