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 tag
E.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 tostring
E = 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With