溫馨提示×

BeautifulSoup怎么添加新標簽

小億
113
2024-05-14 11:14:13
欄目: 編程語言

要向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標簽中。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女