繁体   English   中英

AttributeError:'NoneType'对象没有属性'findChildren'(Beautiful Soup)

[英]AttributeError: 'NoneType' object has no attribute 'findChildren' (Beautiful Soup)

我正在尝试使用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']}]

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')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM