1. from bs4 import BeautifulSoup
  2. def nest_html(html_string, nesting_level=0):
  3. """
  4. Nests HTML structures for internal use without async logic.
  5. Args:
  6. html_string (str): The HTML string to nest.
  7. nesting_level (int): The current nesting level.
  8. Returns:
  9. str: The nested HTML string.
  10. """
  11. soup = BeautifulSoup(html_string, 'html.parser')
  12. def _recursive_nest(element, level):
  13. """Recursive helper function to nest elements."""
  14. if level >= nesting_level:
  15. return element.prettify()
  16. # Create a nested element with appropriate indentation
  17. nested_element = f"{' ' * level}{element.name}" # Indentation
  18. for child in element.children:
  19. if child.name: # Only process elements
  20. nested_element += "\n" + _recursive_nest(child, level + 1)
  21. return nested_element
  22. return _recursive_nest(soup.body, nesting_level) # Start from the body
  23. if __name__ == '__main__':
  24. html = """
  25. <html>
  26. <head>
  27. <title>My Page</title>
  28. </head>
  29. <body>
  30. <h1>Hello, world!</h1>
  31. <p>This is a paragraph.</p>
  32. <div>
  33. <h2>A Subheading</h2>
  34. <ul>
  35. <li>Item 1</li>
  36. <li>Item 2</li>
  37. </ul>
  38. </div>
  39. </body>
  40. </html>
  41. """
  42. nested_html = nest_html(html, nesting_level=1)
  43. print(nested_html)

Add your comment