要在BeautifulSoup中插入一个新标签及其关联值的子元素,你可以使用以下方法:
首先,导入必要的库:
from bs4 import BeautifulSoup
然后,创建一个BeautifulSoup对象:
html = ""
soup = BeautifulSoup(html, 'html.parser')
接下来,创建新的标签并设置其值:
new_tag = soup.new_tag('p')
new_tag.string = 'This is a new paragraph.'
然后,找到要插入子元素的标签:
parent_tag = soup.body
最后,将新标签插入到父标签中:
parent_tag.append(new_tag)
完整的代码示例如下:
from bs4 import BeautifulSoup
html = ""
soup = BeautifulSoup(html, 'html.parser')
new_tag = soup.new_tag('p')
new_tag.string = 'This is a new paragraph.'
parent_tag = soup.body
parent_tag.append(new_tag)
print(soup.prettify())
运行示例代码后,你将会得到以下输出:
This is a new paragraph.
这样就成功地在BeautifulSoup中插入了一个新标签及其关联值的子元素。