Beautiful Soup 简明教程

Beautiful Soup - extend() Method

Method Description

Beautiful Soup 中的 extend() 方法已从版本 4.7 起添加到 Tag 类中。它将列表中的所有元素添加到标记。此方法类似于标准 Python 列表的 extend() 方法 - 它接受一个字符串数组以附加到标记的内容中。

The extend() method in Beautiful Soup has been added to Tag class from version 4.7 onwards. It adds all the elements in a list to the tag. This method is analogous to a standard Python List’s extend() method - it takes in an array of strings to append to the tag’s content.

Syntax

extend(tags)

Parameters

  1. tags − A list of srings or NavigableString objects to be appended.

Return Type

extend() 方法不返回任何新对象。

The extend() method doesn’t return any new object.

Example

from bs4 import BeautifulSoup

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

tag = soup.b
vals = ['World.', 'Welcome to ', 'TutorialsPoint']
tag.extend(vals)
print (soup.prettify())

Output

<b>
   Hello
   World.
   Welcome to
   TutorialsPoint
</b>