Beautiful Soup - insert_before() 方法



方法描述

Beautiful Soup 中的 insert_before() 方法在解析樹中將標籤或字串插入到其他內容的前面。插入的元素成為該元素的直接前驅。插入的元素可以是標籤或字串。

語法

insert_before(*args)

引數

  • args − 一個或多個元素,可以是標籤或字串。

返回值

此 insert_before() 方法不返回任何新物件。

示例 1

以下示例在給定的 HTML 標記字串中的 "Excellent" 之前插入文字 "Here is an"。

from bs4 import BeautifulSoup, NavigableString

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

tag.insert_before("Here is an ")
print (soup.prettify())

輸出

Here is an
<b>
   Excellent
</b>
   Python Tutorial
<u>
   from TutorialsPoint
</u>

示例 2

您還可以將標籤插入到另一個標籤之前。請檢視此示例。

from bs4 import BeautifulSoup, NavigableString

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

輸出

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

示例 3

以下程式碼傳遞多個字串以在 <b> 標籤之前插入。

from bs4 import BeautifulSoup

markup = '<p>There are <b>Tutorials</b> <u>from TutorialsPoint</u></p>'
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.b

tag.insert_before("many ", 'excellent ')
print (soup.prettify())

輸出

<p>
   There are
   many
   excellent
   <b>
      Tutorials
   </b>
   <u>
      from TutorialsPoint
   </u>
</p>
廣告

© . All rights reserved.