为了账号安全,请及时绑定邮箱和手机立即绑定

使用 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 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信