亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 BeautifulSoup 創建帶有嵌套標簽的新標簽

使用 BeautifulSoup 創建帶有嵌套標簽的新標簽

天涯盡頭無女友 2023-10-06 10:54:37
我們如何使用 BeutifulSoup 創建帶有嵌套標簽的新標簽?例如,給定以下 HTML:html = """   <div id="root">   </div>"""例如,所需的輸出是:html = """   <div id="root">      <div id="child">         <div id="grandchild">         </div>      </div>   </div>"""
查看完整描述

2 回答

?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

這是一個相當復雜的代碼,但這就是它可以完成的方法:


from bs4 import BeautifulSoup


html = """

   <div id="root">

   </div>

"""

# parse the root

root = BeautifulSoup(html)


# create the child

child = BeautifulSoup('<div id="child" />')


# create the grandchild under the child, and append grandchild to child

grandchild = child.new_tag('div', attrs={'id': 'grandchild'})

child.div.append(grandchild) 


# create the child under the root, and append child to root

root.new_tag(child.html.contents[0].div)

root.div.append(child.html.contents[0].div)

注意:


如果你打印root:


 [...]

 print(root.prettify()) 

輸出是:


 <html>

   <body>

      <div id="root">

         <div id="child">

           <div id="grandchild">

           </div>

         </div>

      </div>

   </body>

 </html>

這意味著root現在是一個完整的 HTML 文檔。

因此,如果您想用作rootdiv,請確保使用root.div.


最后一行 ( root.div.append) 為空child,因此如果在執行最后一行后打印它:


[...]

print(child.prettify()) 

輸出是:


<html>

  <body>

  </body>

</html>


查看完整回答
反對 回復 2023-10-06
?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

您可以將另一個附加soup到標簽中。例如:


from bs4 import BeautifulSoup



html = """

   <div id="root">

   </div>

"""


to_append = '''

  <div id="child">

     <div id="grandchild">

     </div>

  </div>'''



soup = BeautifulSoup(html, 'html.parser')

soup.select_one('div#root').append(BeautifulSoup(to_append, 'html.parser'))

print(soup.prettify())

印刷:


<div id="root">

 <div id="child">

  <div id="grandchild">

  </div>

 </div>

</div>


查看完整回答
反對 回復 2023-10-06
  • 2 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號