Skip to content

Instantly share code, notes, and snippets.

@tamyiuchau
Last active April 9, 2019 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamyiuchau/1b8391a131f677342c0080bd57c9d4b2 to your computer and use it in GitHub Desktop.
Save tamyiuchau/1b8391a131f677342c0080bd57c9d4b2 to your computer and use it in GitHub Desktop.
abusing with statement to write html in whitespace indentation
from bs4 import BeautifulSoup
from contextlib import contextmanager
__current_soup=[]
@contextmanager
def append(name):
node = __current_soup[0].new_tag(name)
__current_soup.append(node)
global s
s = __current_soup[-1]
yield node
__current_soup.pop()
__current_soup[-1].append(node)
@contextmanager
def new_soup():
node = BeautifulSoup("","lxml")
__current_soup.append(node)
yield node
__current_soup.pop()
if __name__=="__main__":
__node_list=["html","head","body","title","h1"]
html,head,body,title,h1 = [append(i) for i in __node_list]
with new_soup() as file:
with html:
with head:
with title:
s.string="Anyyway"
with body:
with h1:
s.string="this works"
print(file.prettify())
"""
<html>
<head>
<title>
Anyyway
</title>
</head>
<body>
<h1>
this works
</h1>
</body>
</html>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment