Python .contents和.children之间的差异

Python .contents和.children之间的差异,python,beautifulsoup,Python,Beautifulsoup,我读到了。contents返回标记的直接子级,如果我们想迭代这些子级,我们应该使用。children。但我尝试了这两种方法,得到了相同的结果 html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b><

我读到了。contents返回标记的直接子级,如果我们想迭代这些子级,我们应该使用。children。但我尝试了这两种方法,得到了相同的结果

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p></body></html>
"""
soup = BeautifulSoup(html_doc, "html.parser")
title_tag = soup.title

for child in title_tag.children:
    print(child)
for child in title_tag.contents:
    print(child)
html_doc=”“”
睡鼠的故事
睡鼠的故事

从前有三个小姐妹,她们的名字是 , 和 ; 他们住在井底

""" soup=BeautifulSoup(html\u doc,“html.parser”) title\u tag=soup.title 对于title_tag.children中的子项: 印刷品(儿童) 对于title_tag.contents中的子项: 印刷品(儿童)
文档比这要微妙一些。上面说

您可以使用.children生成器迭代标记的子项,而不是将它们作为列表

但是,您可以在for循环中直接迭代列表,并且可以通过调用
iter()
获得迭代器,因此,甚至拥有
.children
属性似乎都是毫无意义的。更仔细地看,下面是如何实现
子项

#Generator methods
@property
def children(self):
    # return iter() to make the purpose of the method clear
    return iter(self.contents)  # XXX This seems to be untested.

是的,这完全没有意义。这两段代码完全相同,只是
用于title\u标记中的child。contents
为列表获取一个迭代器,而
用于title\u标记中的child。children
使用其已交付的迭代器。

考虑到您正在谈论的是BeautifulSoup(您应该给我们一些背景内容!)

如前所述,主要区别在于使用
.contents
可以得到一个列表,而使用
.children
可以得到一个生成器

这似乎没有什么区别,因为您可以对它们进行迭代,但当您处理一组大数据时,您应该始终更喜欢使用生成器来节省计算机内存


想象一下:你有一个10k的文本文件,你需要一次处理每一行。在使用列表时(例如:
将open('t.txt')作为f:lines=f.readlines()
),您将用一些无法立即使用的内容填充整个内存,只是挂在那里花费空间(更不用说,根据您的环境,您可能没有足够的内存…),你会得到一行的时间,根据需要,但没有内存消耗

我得到
名称错误:未定义名称“title\u tag”
。让这成为一个有效的例子怎么样?对不起。好了,完成了!