2017-02-20 31 views
0

我需要將這樣的腳本插入到我的HTML中。我用LXML解析成一棵樹,然後添加一個新的腳本元素,像這樣:如何使用lxml插入JavaScript?

<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

我認爲這個問題是關係到系列化

>>> 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

+0

我從來沒有想到這一點,謝謝。我使用python2.7,但它的工作原理是一樣的。此外,這工作:etree.tostring(腳本,方法='html') – Tim