python - 创建具有 'class' 属性的元素会引发语法错误

标签 python lxml

当我尝试使用 lxml 模块执行此操作时:

div = etree.SubElement(body, "div", class="hmi")

我得到一个:

user@localhost:metk $ sudo python mbscan.py -r 192.168.0.0/24 --hmi
  File "mbscan.py", line 481
    div = etree.SubElement(body, "div", class="hmi")
                                            ^
SyntaxError: invalid syntax

因为class是Python保留用于其他用途的关键字。 IE 这个:

div = etree.SubElement(body, "div", hello="hmi")

工作正常。

我知道 lxml 中有另一个专门为 html 制作的引擎,但为了保留我的 xmlhtml 报告生成器尽可能相似我想知道这里是否没有其他解决方法?

如何创建带有 class 属性的 xml 标记而不影响 Python?

最佳答案

定义属性字典并将其作为 attrib 参数传递。

例如:

>>> from lxml.html import Element, tostring
>>> 
>>> div = Element("div", attrib={"class": "hmi"})
>>> 
>>> print(tostring(div))
<div class="hmi"></div>

请注意,我在这里使用 lxml.html,但同样的想法也适用于 etree

关于python - 创建具有 'class' 属性的元素会引发语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29190100/

相关文章:

python - 删除某个子节点之后的子节点

python - 从单词列表中创建句子 x 次

python - 没有从我的逻辑回归实现中获得正确的系数等高线图?

python - Ansible 错误 : AttributeError: module 'platform' has no attribute 'dist'

python - 如何让 python 窗口以 "Always On Top"运行?

python - lxml:元素上的 XPath 和命名空间

python - SpaCy - ValueError : operands could not be broadcast together with shapes (1, 2) (1,5)

python - ElementTree.write 在第二次传递时没有 pretty_print

python - 如何用另一个索引字符串 Python 替换 String 的所有实例

python - 这个 python lxml 库出了什么问题