使用BeautifulSoup创建带有嵌套标记的新标记

2024-09-27 21:27:46 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用BeutifulSoup创建带有嵌套标记的新标记

例如,给定以下HTML:

html = """
   <div id="root">
   </div>
"""

例如,所需输出为:

html = """
   <div id="root">
      <div id="child">
         <div id="grandchild">
         </div>
      </div>
   </div>
"""

Tags: 标记dividchildhtmlrootgrandchildbeutifulsoup
2条回答

您可以将另一个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>

这是一个相当复杂的代码,但这就是如何做到的:

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文档。
    因此,如果您想使用root作为div,请确保使用root.div访问它

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

    [...]
    print(child.prettify()) 
    

    输出为:

    <html>
      <body>
      </body>
    </html>
    

相关问题 更多 >

    热门问题