Hướng dẫn python pretty print html
I am using lxml.html to generate some HTML. I want to pretty print (with indentation) my final result into an html file. How do I do that? This is what I have tried and got till now
As you can see I am using the
OneCricketeer 160k18 gold badges119 silver badges219 bronze badges asked May 27, 2011 at 9:09
0 I ended up using BeautifulSoup directly. That is something lxml.html.soupparser uses for parsing HTML. BeautifulSoup has a prettify method that does exactly what it says it does. It prettifies the HTML with proper indents and everything. BeautifulSoup will NOT fix the HTML, so broken code, remains broken. But in this case, since the code is being generated by lxml, the HTML code should be at least semantically correct. In the example given in my question, I will have to do this :
Tyrannas 3,7931 gold badge10 silver badges16 bronze badges answered May 29, 2011 at 11:14
bcosynotbcosynot 5,3159 gold badges34 silver badges45 bronze badges 5 Though my answer might not be helpful now, I am dropping it here to act as a reference to anybody else in future.
However, the "sibling" of So one might use it as following:
The output is like this:
answered May 12, 2013 at 9:01
Jayesh BhootJayesh Bhoot 1,4631 gold badge21 silver badges33 bronze badges 4 If you store the HTML as an unformatted string, in a variable
answered Nov 13, 2017 at 7:26
AlexAlex 10.7k6 gold badges61 silver badges71 bronze badges 1 If adding one more dependency is not a problem, you can use the html5print package. The advantage over the other solutions, is that it also beautifies both CSS and Javascript code embedded in the HTML document. To install it, execute:
Then, you can either use it as a command:
or as Python code:
answered Mar 19, 2018 at 20:49
pgmankpgmank 4,7655 gold badges34 silver badges47 bronze badges 1 I tried both BeautifulSoup's
answered May 6, 2018 at 8:02
Vadym PaskoVadym Pasko 2414 silver badges4 bronze badges Under the hood,
So if a node is an element, is not an inline tag and is followed by a sibling node ( answered May 27, 2011 at 15:40
samplebiassamplebias 36.2k6 gold badges103 silver badges102 bronze badges Couldn't you just pipe it into HTML Tidy? Either from the shell or through answered May 27, 2011 at 13:14
tsmtsm 3,4482 gold badges20 silver badges35 bronze badges 3 If you don't care about quirky
HTMLness (e.g. you must support absolutely support those hordes of Netscpae 2.0-using clients, so having answered May 27, 2011 at 12:56
Boaz YanivBoaz Yaniv 6,18620 silver badges29 bronze badges 1 not really my code, I picked it somewhere
I use it with:
answered May 27, 2011 at 15:22
sherpyasherpya 4,7822 gold badges32 silver badges49 bronze badges 0 |