Beautiful Soup 简明教程
Beautiful Soup - insert_before() Method
Method Description
Beautiful soup 中的 insert_before() 方法将标签或字符串插入解析树中其他内容的正前方。插入的元素成为 this one 的直接前继元素。插入的元素可以是标签或字符串。
The insert_before() method in Beautiful soup inserts tags or strings immediately before something else in the parse tree. The inserted element becomes the immediate predecessor of this one. The inserted element can be a tag or a string.
Return Value
此 insert_before() 方法不返回任何新对象。
This insert_before() method doesn’t return any new object.
Example 1
以下示例将文本 "Here is an" 插入给定 HTML 标记字符串中的 "Excellent" 前方。
The following example inserts a text "Here is an" before "Excellent in the given HTML markup string.
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())
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</u>'
soup = BeautifulSoup(markup, 'html.parser')
tag = soup.b
tag1 = soup.new_tag('b')
tag1.string = "Python "
tag.insert_before(tag1)
print (soup.prettify())
Example 3
以下代码传递多个字符串,将它们插入 <b> 标签之前。
The following code passes more than one strings to be inserted before the <b> tag.
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())