Beautiful Soup 简明教程

Beautiful Soup - children Property

Method Description

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

Syntax

Tag.children

Return value

该属性返回一个生成器,您可以用它迭代 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 属性。

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> 标记并获取子项列表。

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