Python的ElementTree,如何在段落中创建链接

Python's ElementTree, how to create links in a paragraph

我有一个网站,我正在 运行 基于 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:格式不正确”错误。在 ElementTree 中有没有更好的方法来做到这一点?我确信那里有更好的扩展,但我的工作环境仅限于 Python 2.7 和标准库。任何帮助,将不胜感激。谢谢! 埃文

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

所以尝试用 &amp; 替换 & 看看是否可行。