Last active
April 9, 2019 06:19
-
-
Save tamyiuchau/1b8391a131f677342c0080bd57c9d4b2 to your computer and use it in GitHub Desktop.
abusing with statement to write html in whitespace indentation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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