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

混江龙づ霸主 提交于 2019-12-12 11:22:55

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/31143716/does-the-e-factory-of-lxml-support-dynamically-generated-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!