Is there a way of creating the tags dynamically with the E-factory of lxml? For instance I get a syntax error for the following code:
E.BODY(E.TABLE(for row_num in range(len(ws.rows)):row = ws.rows[row_num]# create a tr tagE.TR(for cell_num in range(len(row)):cell = row[cell_num]
I get the following error:
for row_num in range(len(ws.rows)):^SyntaxError: invalid syntax
In order to create multiple child nodes, pass multiple positional or keyword arguments.
Working example:
from lxml.builder import ElementMaker
from lxml.html import tostringE = ElementMaker()body = E.BODY(E.TABLE(*[E.TR(*[E.TD("%s %s" % (row_num, col_num)) for col_num in range(3)]) for row_num in range(2)])
)print tostring(body, pretty_print=True)
Prints:
<BODY><TABLE>
<TR>
<TD>0 0</TD>
<TD>0 1</TD>
<TD>0 2</TD>
</TR>
<TR>
<TD>1 0</TD>
<TD>1 1</TD>
<TD>1 2</TD>
</TR>
</TABLE></BODY>
As a side note, from what I understand you want to create an HTML file filled with data coming from a parsed excel file. Instead of making elements with lxml
, you might better and easier solve it with a template engine like jinja2
or mako
.