如何使用lxml插入JavaScript?

时间:2017-02-20 20:20:43

标签: python lxml

我需要在我的HTML中插入这样的脚本。我使用lxml解析成树,然后添加一个新的脚本元素,如下所示:

<body>
  <script type="text/javascript">
    window.location="http://www.example.com/?one&two&three"
  </script>

这就是我想要的结果,但是&符号在写入时被转义。 有没有办法用lxml得到我想要的东西?

<body>
  <script type="text/javascript">
    window.location="http://www.example.com/?one&amp;two&amp;three"
  </script>

1 个答案:

答案 0 :(得分:1)

我认为问题与序列化有关

>>> from lxml import etree, html
>>> script = etree.Element('script')
>>> script.text = 'window.location="http://www.example.com/?one&two&three"'
>>> etree.tostring(script)
b'<script>window.location="http://www.example.com/one&amp;two&amp;three"</script>'
>>> html.tostring(script)
b'<script>window.location="http://www.example.com/?one&two&three"</script>'

我的python版本3.5和lxml == 3.7.3