【问题标题】:how to make beautifulsoup encode and decode the contents of a script tag如何让 beautifulsoup 对脚本标签的内容进行编码和解码
【发布时间】:2012-11-20 06:25:09
【问题描述】:

我正在尝试使用 beautifulsoup 来解析 html,但每当我点击带有内联脚本标签的页面时,beautifulsoup 都会对内容进行编码,但最终不会将其解码。

这是我使用的代码:

from bs4 import BeautifulSoup

if __name__ == '__main__':

    htmlData = '<html> <head> <script type="text/javascript"> console.log("< < not able to write these & also these >> "); </script> </head> <body> <div> start of div </div> </body> </html>'
    soup = BeautifulSoup(htmlData)
    #... using BeautifulSoup ...
    print(soup.prettify() )

我想要这个输出:

<html>
 <head>
  <script type="text/javascript">
   console.log("< < not able to write these & also these >> ");
  </script>
 </head>
 <body>
  <div>
   start of div
  </div>
 </body>
</html>

但是我得到了这个输出:

<html>
 <head>
  <script type="text/javascript">
   console.log("&lt; &lt; not able to write these &amp; also these &gt;&gt; ");
  </script>
 </head>
 <body>
  <div>
   start of div
  </div>
 </body>
</html>

【问题讨论】:

  • Beautiful Soup 3 中有一个 bug filed 用于此问题。Beautiful Soup 4 中似乎仍然存在该错误。您可能需要 file 一个错误报告。

标签: python tags beautifulsoup


【解决方案1】:

你不妨试试lxml:

import lxml.html as LH

if __name__ == '__main__':
    htmlData = '<html> <head> <script type="text/javascript"> console.log("< < not able to write these & also these >> "); </script> </head> <body> <div> start of div </div> </body> </html>'
    doc = LH.fromstring(htmlData)
    print(LH.tostring(doc, pretty_print = True))

产量

<html>
<head><script type="text/javascript"> console.log("< < not able to write these & also these >> "); </script></head>
<body> <div> start of div </div> </body>
</html>

【讨论】:

    【解决方案2】:

    你可以这样做:

    htmlCodes = (
    ('&', '&amp;'),
    ('<', '&lt;'),
    ('>', '&gt;'),
    ('"', '&quot;'),
    ("'", '&#39;'),
    )
    
    for i in htmlCodes:
        soup.prettify().replace(i[1], i[0])
    

    【讨论】:

    • -1。这有很多错误。首先,您为每次迭代调用 prettify,丢弃先前替换的结果。其次,您破坏了任何不在 javascript 部分中的字符实体引用。
    猜你喜欢
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多