Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the E-factory of lxml support dynamically generated data?

Tags:

python

html

lxml

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
like image 613
user3293692 Avatar asked Jun 30 '15 16:06

user3293692


1 Answers

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.

like image 112
alecxe Avatar answered Oct 05 '22 22:10

alecxe