Reputation: 1621
How to automatically generate tabs to get a proper tree view on a generated HTML file?
For example, I've got a code like this:
def creating_html(self):
something ='''<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
'''
file.write(something)
This code will generate code with proper tabs etc. but I feel my code is really messy because of that and also I think that I'm wasting time to check for a good format. So I was thinking about something like this, to make my code little bit cleaner.
def creating_html(self):
something ='''
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
'''
file.write(something)
but now the format is of course invalid.
I was searching for a good solution and one of them is just open this HTML file after generating it with PyCharm and use shortcut Ctrl+Alt+L. I'm looking for a solution to do it automatically.
Upvotes: 0
Views: 699
Reputation: 101
You may use Beautiful Soup 4 installing it with pip and use it like follows:
from bs4 import BeautifulSoup
something ='''
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
'''
messed_code= BeautifulSoup(something, 'html.parser')
file.write(messed_code.prettify())
Personally, I think the string looks better in the first case as far as it's more readable
Upvotes: 2
Reputation: 1097
from lxml import etree, html
html_string ='''
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
'''
html_object = html.fromstring(html_string)
file.write(etree.tostring(html_object, pretty_print=True))
Upvotes: 1