温馨提示×

BeautifulSoup怎么添加新标签

小亿
107
2024-05-14 11:14:13
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要向BeautifulSoup中添加新标签,首先需要创建一个标签对象,然后使用append()方法将该标签添加到指定的父标签中。

以下是一个示例代码,向BeautifulSoup中添加一个新的div标签:

from bs4 import BeautifulSoup

html = "<html><body><h1>Hello, World!</h1></body></html>"
soup = BeautifulSoup(html, 'html.parser')

# 创建一个新的div标签
new_div = soup.new_tag('div')
new_div.string = 'This is a new div tag.'

# 将新的div标签添加到body标签中
soup.body.append(new_div)

# 打印修改后的HTML内容
print(soup.prettify())

运行上述代码后,输出结果将会是:

<html>
 <body>
  <h1>
   Hello, World!
  </h1>
  <div>
   This is a new div tag.
  </div>
 </body>
</html>

可以看到,新的div标签已经成功添加到了body标签中。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:qt tabbar怎么添加新标签

0