Beautiful Soup 简明教程

Beautiful Soup - append() Method

Method Description

Beautiful Soup 中的 append() 方法在当前标记对象的末尾添加给定的字符串或另一个标记。该 append() 方法的工作方式类似于 Python 的列表对象的 append() 方法。

The append() method in Beautiful Soup adds a given string or another tag at the end of the current Tag object’s contents. The append() method works similar to the append() method of Python’s list object.

Syntax

append(obj)

Parameters

  1. obj − any PageElement, may be a string, a NavigableString object or a Tag object.

Return Type

该 append() 方法不返回新对象。

The append() method doesn’t return a new object.

Example 1

在以下示例中,HTML 脚本有一个 <p> 标记。使用 append() 附加文本。在以下示例中,HTML 脚本有一个 <p> 标记。使用 append() 附加文本。

In the following example, the HTML script has a <p> tag. With append(), additional text is appended.In the following example, the HTML script has a <p> tag. With append(), additional text is appended.

from bs4 import BeautifulSoup

markup = '<p>Hello</p>'
soup = BeautifulSoup(markup, 'html.parser')
print (soup)
tag = soup.p

tag.append(" World")
print (soup)

Output

<p>Hello</p>
<p>Hello World</p>

Example 2

通过 append() 方法,你可以在现有标记的末尾添加新标记。首先使用 new_tag() 方法创建一个新标记对象,然后将其传递给 append() 方法。

With the append() method, you can add a new tag at the end of an existing tag. First create a new Tag object with new_tag() method and then pass it to the append() method.

from bs4 import BeautifulSoup, Tag

markup = '<b>Hello</b>'
soup = BeautifulSoup(markup, 'html.parser')

tag = soup.b
tag1 = soup.new_tag('i')
tag1.string = 'World'
tag.append(tag1)
print (soup.prettify())

Output

   <b>
      Hello
   <i>
      World
   </i>
</b>

Example 3

如果你必须将字符串添加到文档,你可以附加一个 NavigableString 对象。

If you have to add a string to the document, you can append a NavigableString object.

from bs4 import BeautifulSoup, NavigableString

markup = '<b>Hello</b>'
soup = BeautifulSoup(markup, 'html.parser')

tag = soup.b
new_string = NavigableString(" World")
tag.append(new_string)
print (soup.prettify())

Output

<b>
   Hello
   World
</b>