Beautiful Soup 简明教程

Beautiful Soup - children Property

Method Description

Beautiful Soup 库中的 Tag 对象具有 children 属性。它返回用于迭代直接的子元素和文本节点(即 Navigable String)的生成器。

The Tag object in Beautiful Soup library has children property. It returns a generator used to iterate over the immediate child elements and text nodes (i.e. Navigable String).

Syntax

Tag.children

Return value

该属性返回一个生成器,您可以用它迭代 PageElement 的直接子项。

The property returns a generator with which you can iterate over direct children of the PageElement.

Example 1

from bs4 import BeautifulSoup, NavigableString

markup = '''
   <div id="Languages">
      <p>Java</p> <p>Python</p> <p>C++</p>
   </div>
'''
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.div
children = tag.children
for child in children:
   print (child)

Output

<p>Java</p>

<p>Python</p>

<p>C++</p>

Example 2

soup 对象也拥有 children 属性。

The soup object too bears the children property.

from bs4 import BeautifulSoup, NavigableString

markup = '''
   <div id="Languages">
      <p>Java</p> <p>Python</p> <p>C++</p>
   </div>
'''
soup = BeautifulSoup(markup, 'html.parser')

children = soup.children
for child in children:
   print (child)

Output

<div id="Languages">
<p>Java</p> <p>Python</p> <p>C++</p>
</div>

Example 3

在以下示例中,我们将 NavigableString 对象追加到 <p> 标记并获取子项列表。

In the following example, we append NavigableString objects to the <p> Tag and get the list of children.

from bs4 import BeautifulSoup, NavigableString

markup = '''
   <div id="Languages">
      <p>Java</p> <p>Python</p> <p>C++</p>
   </div>
'''
soup = BeautifulSoup(markup, 'html.parser')
soup.p.extend(['and', 'JavaScript'])
children = soup.p.children
for child in children:
    print (child)

Output

Java
and
JavaScript