AttributeError:' NoneType'对象没有属性" findChildren' (美丽的汤)

时间:2015-07-06 05:23:56

标签: python beautifulsoup attributeerror

我试图使用Beautiful Soup来构建包含许多不同博客帖子ID的标签的字典。

我首先写了一个函数来处理一个帖子ID:

def tags(id_):
        r = h.unescape(requests.get('https://example.com/category/'+id_).text)
        soup = BeautifulSoup(r)
        return  {"id": id_, "tags": [tag.text for tag in soup.find("ul",{"class":\
        "tags"}).findChildren("a")]}

..我得到了我所期待的:

tags('a123')
{'id': 'a123', 'tags': [u'food and drink', u'beer', u'sonoma county']}

我修改了函数以遍历帖子ID列表,例如:

postids = ['a123', 'b456', 'c789']
tags_dict = {}
def tags_list(postids):
    for id_ in postids:    
        r = h.unescape(requests.get('https://example.com/category/'+id_).text)
        soup = BeautifulSoup(r)
        tags_dict['id'] = id_
        tags_dict['tags'] = [tag.text for tag in soup.find('ul',{'class':\
        "tags"}).findChildren('a')]

当我运行tags_list(postids)时,我得到了:

AttributeError: 'NoneType' object has no attribute 'findChildren'

......我不确定为什么。有关如何修复的任何想法?或者是否有更好的方法可以完全接近?

编辑:以下是我最终使用的函数的最终版本。我想要一个列表而不是字典,所以我也做了这个改变。

postids = ['a123', 'b456', 'c789']
def tags_list(postids):
    tags_data = []
    for id_ in postids:    
        r = h.unescape(requests.get('https://example.com/category/'+id_).text)
        soup = BeautifulSoup(r)
        data = {}
        data['postid'] = id_
        data['tags'] = [child.text
                     for tag in [soup.find('ul',{'class': "tags"})]
                     if tag
                     for child in tag.findChildren('a')]
        tags_data.append(data)
    return tags_data

这是一个示例输出:

[{'postid': 'a123', 'tags': [u'food and drink', u'beer', u'sonoma']},
 {'postid': 'b456', 'tags': [u'travel', u'road trips', u'camping']},
 {'postid': 'c789', 'tags': [u'cooking', u'grilling', u'steak']}]

1 个答案:

答案 0 :(得分:0)

soup.find('ul',{'class': "tags"})正在返回None

如果要在列表推导中使用此功能,则需要在使用之前过滤掉None的值。

您可以将值放在列表中,以便过滤它:

tags_dict['tags'] = [child.text
                     for tag in [soup.find('ul',{'class': "tags"})]
                     if tag
                     for child in tag.findChildren('a')]