from bs4 import BeautifulSoup
def nest_html(html_string, nesting_level=0):
"""
Nests HTML structures for internal use without async logic.
Args:
html_string (str): The HTML string to nest.
nesting_level (int): The current nesting level.
Returns:
str: The nested HTML string.
"""
soup = BeautifulSoup(html_string, 'html.parser')
def _recursive_nest(element, level):
"""Recursive helper function to nest elements."""
if level >= nesting_level:
return element.prettify()
# Create a nested element with appropriate indentation
nested_element = f"{' ' * level}{element.name}" # Indentation
for child in element.children:
if child.name: # Only process elements
nested_element += "\n" + _recursive_nest(child, level + 1)
return nested_element
return _recursive_nest(soup.body, nesting_level) # Start from the body
if __name__ == '__main__':
html = """
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello, world!</h1>
<p>This is a paragraph.</p>
<div>
<h2>A Subheading</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
</body>
</html>
"""
nested_html = nest_html(html, nesting_level=1)
print(nested_html)
Add your comment