Python lxml html 生成器

Python lxml html builder

大家好,我想在 python 中制作一个 html。我阅读了 xml 和 python 请求。我计算了一个属性的元素。

count = len(nodeData.xpath("//user[@condition='good']"))
print (count)`

像这样。

但现在我想得到一个table,其中保留计数的数量。

nodeRow = html.TR(html.TD(count , style="background-color:#FF0000")
nodeTable.append(nodeRow)

print etree.tostring(nodeTable)
with open("out3.html", "wb") as f:
    f.write(etree.tostring(nodeTable))

但这不起作用。错误是

TypeError: bad argument type: int(2746)

错误代码非常清楚 - 您不能将字符串放入元素的文本内容中。因为你有一个 int,所以 Python 犹豫不决。先转为字符串:

nodeRow = html.TR(html.TD(str(count) , style="background-color:#FF0000")

尽管如此,您还是应该考虑使用模板库,因为它可以解决这些小障碍,并且可以更自然地编写更长的 HTML 片段。