6

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
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
user3293692
  • 567
  • 1
  • 5
  • 14

1 Answers1

6

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.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thanks a lot! Yes I am trying to create an HTML file with data from the excel file. Can you please provide me with a good mako tutorial as a starting point or maybe provide with an example of how I can do it. – user3293692 Jun 30 '15 at 17:31
  • @user3293692 the idea is pretty simple, create the template with pre-defined placeholders and render it with the data coming into the context from an excel file. If you struggle with it, consider making a separate question. But be sure you at least make an attempt to solve it on your own. Thanks. To close this topic, consider marking the answer as accepted. – alecxe Jul 01 '15 at 02:13