如何将JavaScript插入< script/>元素? [英] How to insert JavaScript into <script/> element?
问题描述
我所拥有的是:
from lxml import etree
myscript = "if(0 < 1){alert(\"Hello World!\");}"
html = etree.fromstring("<script></script>")
for element in html.findall('//script'):
element.text = myscript
result = etree.tostring(html)
我得到的是:
>>> result
'<script>if(0 < 1){alert("Hello World!");}</script>'
我想要的是未转义的 JavaScript:
What I want is unescaped JavaScript:
>>> result
'<script>if(0 < 1){alert("Hello World!");}</script>'
推荐答案
您不能. lxml.etree
和 ElementTree 是XML解析器,因此无论您想要什么解析或与其创建必须是有效的XML.在某些节点文本中未转义的<
无效XML.它是有效的HTML,但不是有效的XML.
You can’t. lxml.etree
and ElementTree are XML parsers, so whatever you want to parse or create with them has to be valid XML. And an unescaped <
inside some node text is not valid XML. It’s valid HTML but not valid XML.
这就是为什么在XHTML中通常必须在<script>
标记内添加CDATA块,以便可以在其中放置任何而不用担心有效的XML结构.
That’s why in XHTML, you usually had to add CDATA blocks inside <script>
tags, so you could put whatever in there without having to worry about valid XML structure.
但是,在您的情况下,您只想生成HTML,为此,您应该使用HTML解析器.例如 BeautifulSoup :
But in your case, you just want to produce HTML, and for that, you should use an HTML parser. For example BeautifulSoup:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<script></script>')
>>> soup.find('script').string = 'if(0 < 1){alert("Hello World!");}'
>>> str(soup)
'<script>if(0 < 1){alert("Hello World!");}</script>'
这篇关于如何将JavaScript插入< script/>元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!