【问题标题】:Adding html tags to text of XML.ElementTree Elements in Python在 Python 中将 html 标签添加到 XML.ElementTree 元素的文本
【发布时间】:2014-11-01 20:42:40
【问题描述】:

我正在尝试使用 python 脚本使用 XML.etree.ElementTree 模块从数据表中生成带有文本的 HTML 文档。我想格式化一些单元格以包含 html 标签,通常是 <br /><sup></sup> 标签。当我生成一个字符串并将其写入文件时,我相信 XML 解析器正在将这些标签转换为单个字符。输出将标签显示为文本,而不是将它们作为标签处理。这是一个简单的例子:

import xml.etree.ElementTree as ET

root = ET.Element('html')
   #extraneous code removed
td = ET.SubElement(tr, 'td')
td.text = 'This is the first line <br /> and the second'

tree = ET.tostring(root)
out = open('test.html', 'w+')           
out.write(tree)                     
out.close()

当您打开生成的“test.html”文件时,它会显示与输入完全相同的文本字符串:“这是第一行
和第二行”。

HTML 文档本身在源代码中显示了问题。似乎解析器将标记中的“小于”和“大于”符号替换为这些符号的 HTML 表示:

    <!--Extraneous code removed-->
<td>This is the first line %lt;br /&gt; and the second</td>

显然,我的意图是让文档处理标签本身,而不是将其显示为文本。我不确定是否可以传递不同的解析器选项以使其正常工作,或者是否应该使用不同的方法。如果可以解决问题,我愿意使用其他模块(例如 lxml)。为了方便,我主要使用内置的 XML 模块。

我发现唯一可行的方法是在编写文件之前用re 替换修改最终字符串:

tree = ET.tostring(root)
tree = re.sub(r'&lt;','<',tree)
tree = re.sub(r'&gt;','>',tree)

这可行,但似乎可以通过在xml 中使用不同的设置来避免这种情况。有什么建议吗?

【问题讨论】:

    标签: python html xml elementtree


    【解决方案1】:

    您可以将tail 属性与tdbr 一起使用来构建您想要的文本:

    import xml.etree.ElementTree as ET
    
    
    root = ET.Element('html')
    table = ET.SubElement(root, 'table')
    tr = ET.SubElement(table, 'tr')
    td = ET.SubElement(tr, 'td')
    td.text = "This is the first line "
    # note how to end td tail
    td.tail = None
    br = ET.SubElement(td, 'br')
    # now continue your text with br.tail
    br.tail = " and the second"
    
    tree = ET.tostring(root)
    # see the string
    tree
    '<html><table><tr><td>This is the first line <br /> and the second</td></tr></table></html>'
    
    with open('test.html', 'w+') as f:
        f.write(tree)
    
    # and the output html file
    cat test.html
    <html><table><tr><td>This is the first line <br /> and the second</td></tr></table></html>
    

    附带说明,要包含&lt;sup&gt;&lt;/sup&gt; 并附加文本但仍在&lt;td&gt; 内,使用tail 也会产生预期效果:

    ...
    td.text = "this is first line "
    sup = ET.SubElement(td, 'sup')
    sup.text = "this is second"
    # use tail to continue your text
    sup.tail = "well and the last"
    
    print ET.tostring(root)
    <html><table><tr><td>this is first line <sup>this is second</sup>well and the last</td></tr></table></html>
    

    【讨论】:

    • 这很完美!它确实为我的产品添加了一些代码,但最终结果更加可预测。
    • @EricDauenhauer,很高兴它有帮助:)
    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    相关资源
    最近更新 更多