如何使beautifulsoup对脚本标记的内容进行编码和解码

2024-04-26 14:38:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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() )

我想要这个输出:

^{pr2}$

但我得到的输出是:

<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>

Tags: textdivloghtmltypescriptnotbody
2条回答

您可能想试试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))

收益率

^{pr2}$

你可以这样做:

htmlCodes = (
('&', '&amp;'),
('<', '&lt;'),
('>', '&gt;'),
('"', '&quot;'),
("'", '&#39;'),
)

for i in htmlCodes:
    soup.prettify().replace(i[1], i[0])

相关问题 更多 >