Beautiful Soup 简明教程

Beautiful Soup - insert() Method

Method Description

Beautiful Soup 中的 insert() 方法在标签元素的子项列表中,在指定位置添加一个元素。Beautiful Soup 中的 insert() 方法的行为,类似于在 Python 列表对象上的 insert() 方法。

The insert() method in Beautiful Soup add an element at the given position in a the list of children of a Tag element. The insert() method in Beautiful Soup behaves similar to insert() on a Python list object.

Syntax

insert(position, child)

Parameters

  1. position − The position at which the new PageElement should be inserted.

  2. child − A PageElement to be inserted.

Return Type

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

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

Example 1

在以下示例中,新字符串被添加到 <b> 标记,位置为 1。结果解析的文档显示结果。

In the following example, a new string is added to the <b> tag at position 1. The resultant parsed document shows the result.

from bs4 import BeautifulSoup, NavigableString

markup = '<b>Excellent </b><u>from TutorialsPoint</u>'
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.b

tag.insert(1, "Tutorial ")
print (soup.prettify())

Output

<b>
   Excellent
   Tutorial
</b>
<u>
   from TutorialsPoint
</u>

Example 2

在下面的示例中,insert() 方法被用于依次将列表中的字符串插入到 HTML 标记中的 <p> 标签。

In the following example, the insert() method is used to successively insert strings from a list to a <p> tag in HTML markup.

from bs4 import BeautifulSoup, NavigableString

markup = '<p>Excellent Tutorials from TutorialsPoint</p>'
soup = BeautifulSoup(markup, 'html.parser')
langs = ['Python', 'Java', 'C']
i=0
for lang in langs:
   i+=1
   tag = soup.new_tag('p')
   tag.string = lang
   soup.p.insert(i, tag)


print (soup.prettify())

Output

<p>
   Excellent Tutorials from TutorialsPoint
   <p>
   Python
   </p>
   <p>
      Java
   </p>
   <p>
      C
   </p>
</p>