【问题标题】:How to stop BeautifulSoup escaping inline javascript如何阻止 BeautifulSoup 转义内联 javascript
【发布时间】:2013-04-03 11:41:49
【问题描述】:

我发现 BeautifulSoup 4 似乎转义了内联 javascript 中的某些字符:

>>> print s
<DOCTYPE html>
<html>
<body>
<h1>Test page</h1>
<script type="text/javascript">
//<!--
if (4 > 3 && 3 < 4) {
        console.log("js working");
}
//-->
</script>
</body>
</html>
>>> import bs4
>>> soup = bs4.BeautifulSoup(s, 'html5lib')
>>> print soup
<html><head></head><body><doctype html="">


<h1>Test page</h1>
<script type="text/javascript">
//&lt;!--
if (4 &gt; 3 &amp;&amp; 3 &lt; 4) {
        console.log("js working");
}
//--&gt;
</script>

</doctype></body></html>
>>> print soup.prettify()
<html>
 <head>
 </head>
 <body>
  <doctype html="">
   <h1>
    Test page
   </h1>
   <script type="text/javascript">
    //&lt;!--
if (4 &gt; 3 &amp;&amp; 3 &lt; 4) {
        console.log("js working");
}
//--&gt;
   </script>
  </doctype>
 </body>
</html>

万一在上面丢失了,关键问题是:

if (4 > 3 && 3 < 4)

转换成:

if (4 &gt; 3 &amp;&amp; 3 &lt; 4)

效果不是特别好……

我尝试了prettify() 方法中包含的格式化程序,但没有成功。

那么知道如何阻止 javascript 被转义吗?或者如何在输出前取消转义?

【问题讨论】:

  • 请注意,它应该是&lt;!-- //,而不是// &lt;!--。但对输出没有影响。
  • &lt;!-- --&gt; cmets 在 Javascript 中实际上是无用的,因为 Javascript 可以很好地利用 &lt;&amp;&gt; 字符。您真的应该使用&lt;![CDATA[]]&gt; 来正确“转义”&lt;script&gt; 标记的内容。
  • 这是解析器的问题;它不会将内容视为评论,因此 &lt;!----&gt; 前缀和后缀被转义。
  • @MartijnPieters - 无论我使用哪个版本的评论,或者如果我不使用评论,关键问题是 if 语句内容被转义。我将更新问题以使其更清楚。

标签: python escaping beautifulsoup


【解决方案1】:

编辑:此错误已在 2013 年 5 月 30 日发布的 4.2.0 中修复。

>>> import bs4
>>> bs4.__version__
'4.2.0'
>> s = """<DOCTYPE html>
... <html>
... <body>
... <h1>Test page</h1>
... <script type="text/javascript">
... //<!--
... if (4 > 3 && 3 < 4) {
...     console.log("js working");
... }
... //-->
... </script>
... </body>
... </html>
... """
>>> soup = bs4.BeautifulSoup(s)
>>> print soup
<html><body><doctype html="">
<h1>Test page</h1>
<script type="text/javascript">
//<!--
if (4 > 3 && 3 < 4) {
    console.log("js working");
}
//-->
</script>
</doctype></body></html>

如果您因某种原因无法使用 answer。在我看来你可以做类似的事情:走树,在所有标签上使用prettyify(),除了script标签,你以某种方式发出而不转义。

【讨论】:

    猜你喜欢
    • 2012-09-14
    • 2018-10-22
    • 2017-04-05
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    相关资源
    最近更新 更多