3

我发现 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被转义吗?或者如何在输出之前取消它?

4

1 回答 1

2

编辑:此错误已在 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>

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

于 2013-05-09T21:25:49.497 回答