【问题标题】:Python's ElementTree, how to create links in a paragraphPython ElementTree,如何在段落中创建链接
【发布时间】:2025-12-21 01:15:07
【问题描述】:

我正在构建一个使用 Python 2.7 并使用 ElementTree 动态构建 HTML 的网站。我可以毫无问题地创建元素并将它们附加到树中。这是我必须在我被难住的大段落中间插入链接的地方。当它在文本中完成时,这很容易,但这是通过 XML 完成的。这就是我的意思:

示例文本:

lawLine = "..., a vessel as defined in Section 21 of the Harbors and Navigation Code which is inhabited and designed for habitation, an inhabited floating home as defined in subdivision (d) of Section 18075.55 of the Health and Safety Code, ..."

要将该文本作为 H4 样式文本添加到 HTML,我通常使用:

      h4 = ET.Element('h4')
      htmlTree.append(h4)
      h4.text = lawLine

我需要在单词“Section”和与之关联的数字处添加链接,但我不能简单地在段落中间创建一个新元素“a”并将其添加到 HTML 树中,所以我'正在尝试将该片段构建为文本,然后执行 ET.fromstring 并将其附加到树中:

      thisLawType = 'PC'
      matches = re.findall(r'Section [0-9.]*', lawLine)
      if matches:
          lawLine = """<h4>{0}</h4>""".format(lawLine)
          for thisMatch in matches:
              thisMatchLinked = """<a href="./index.py?lawtype={0}&lawnumber={1}">{2}</a>""".format(thisLawType, thisMatch.replace('Section ',''), thisMatch)
              lawLine = lawLine.replace(thisMatch, thisMatchLinked)
          htmlBody.append(ET.fromstring(lawLine))

我在执行 ET.fromstring 时收到“xml.etree.ElementTree.ParseError: not well-formed”错误。在 ElementTree 中有没有更好的方法来做到这一点?我确信那里有更好的扩展,但我的工作环境仅限于 Python 2.7 和标准库。任何帮助,将不胜感激。谢谢! 埃文

【问题讨论】:

    标签: python html elementtree


    【解决方案1】:

    由于thisMatchLinked 中存在&amp;amp;,您生成的xml 确实格式不正确。它是需要转义的特殊字符之一 (see an interesting explanation here)。

    所以尝试将&amp;amp; 替换为&amp;amp;,看看是否有效。

    【讨论】:

    • 优秀。谢谢!