2017-02-20 9 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(script、method = 'html') – Tim

関連する問題