Beautiful Soup 简明教程

Beautiful Soup - insert_after() Method

Method Description

Beautiful 汤中的 insert_after() 方法在解析树中的某个元素后立即插入标签或字符串。插入的元素成为该元素的直接后继。插入的元素可以是标签或字符串。

The insert_after() method in Beautiful soup inserts tags or strings immediately after something else in the parse tree. The inserted element becomes the immediate successor of this one. The inserted element can be a tag or a string.

Syntax

insert_after(*args)

Parameters

  1. args − One or more elements, may be tag or a string.

Return Value

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

This insert_after() method doesn’t return any new object.

Example 1

以下代码在第一个 <b> 标签后插入字符串"Python"。

Following code inserts a string "Python" after the first <b> tag.

from bs4 import BeautifulSoup

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

tag.insert_after("Python ")
print (soup.prettify())

Output

<p>
   An
   <b>
      Excellent
   </b>
   Python
   Tutorial
   <u>
      from TutorialsPoint
   </u>
</p>

Example 2

您还可以在另一个标签前插入标签。请看这个示例。

You can also insert a tag before another tag. Take a look at this example.

from bs4 import BeautifulSoup, NavigableString

markup = '<P>Excellent <b>Tutorial</b> from TutorialsPoint</p>'
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.b
tag1 = soup.new_tag('b')
tag1.string = "on Python "
tag.insert_after(tag1)
print (soup.prettify())

Output

<p>
   Excellent
   <b>
      Tutorial
   </b>
   <b>
      on Python
   </b>
   from TutorialsPoint
</p>

Example 3

可以在某个标签后插入多个标签或字符串。

Multiple tags or strings can be inserted after a certain tags.

from bs4 import BeautifulSoup, NavigableString

markup = '<P>Excellent <b>Tutorials</b> from TutorialsPoint</p>'
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.p
tag1 = soup.new_tag('i')
tag1.string = 'and Java'
tag.insert_after("on Python", tag1)
print (soup.prettify())

Output

<p>
   Excellent
   <b>
      Tutorials
   </b>
   from TutorialsPoint
</p>
on Python
<i>
   and Java
</i>