lxml的电子工厂是否支持动态生成的数据? [英] Does the E-factory of lxml support dynamically generated data?

查看:79
本文介绍了lxml的电子工厂是否支持动态生成的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过lxml的E工厂动态创建标签?例如,我收到以下代码的语法错误:

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]

我收到以下错误:

   for row_num in range(len(ws.rows)):
     ^
   SyntaxError: invalid syntax

推荐答案

为了创建多个子节点,请将

In order to create multiple child nodes, pass multiple positional or keyword arguments.

工作示例:

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)

打印:

<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>


作为一个旁注,据我了解,您想创建一个HTML文件,其中填充了来自解析的excel文件的数据.与其使用lxml制作元素,不如使用 mako .


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.

这篇关于lxml的电子工厂是否支持动态生成的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆