Python lxml library fails to parse < and >

妖精的绣舞 提交于 2019-12-22 12:50:47

问题


I have an XSLT with javascript in it which uses "&lt ;" and "&gt ;" inside for loop

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
  <head> </head>
  <body>
    <script language="javascript" type="text/javascript">
  function example() {
        var trs = document.getElementsByTagName("tr");
    for (var i = 0; i &lt; trs.length; i++) {
    }
      }
     </script>
  </body>
</html>

I am using PYTHON LXML library to generate HTML using XSLT and XML.

import lxml.etree as ET
xml = ET.parse('sample.xml')
xslt = ET.parse('sample.xsl')
transform = ET.XSLT(xslt)
content = transform(xml)
f = open('output.html','w')
f.write(ET.tostring(content , pretty_print=True))
f.close()

But LXML is unable to replace special characters in the output HTML file

&lt ; to '<' and &gt ; to '>'

Is there any standard practice using LXML to replace "&lt ;" to '<' ?

To over come this issue I have to write another piece of code before writing to the file.

content = content.replace("&gt;", ">")
content = content.replace("&lt;", "<")

回答1:


In order to decode/convert HTML entities, you should use method="html" in tostring() call:

ET.tostring(content, method="html", pretty_print=True)

or:

lxml.html.tostring(content, pretty_print=True)

DEMO:

from lxml import etree


text = """<html>
  <body>
    <script> 1 &lt; 2 </script>
  </body>
</html>
"""

tree = etree.fromstring(text)
print etree.tostring(tree, method="html")

prints:

<html>
  <body>
    <script> 1 < 2 </script>
  </body>
</html>



回答2:


You can also just surround the script contents in a CDATA wrapper to stop it getting eaten, like so:

<script language="javascript" type="text/javascript">
  <![CDATA[
    function example() {
          var trs = document.getElementsByTagName("tr");
      for (var i = 0; i < trs.length; i++) {
      }
    }
  ]]>
</script>


来源:https://stackoverflow.com/questions/19017253/python-lxml-library-fails-to-parse-lt-and-gt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!