首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何对脚本标签的内容进行编码和解码

如何对脚本标签的内容进行编码和解码
EN

Stack Overflow用户
提问于 2012-12-03 02:13:54
回答 2查看 950关注 0票数 4

我试着用漂亮汤来解析html,但是每当我点击一个带有内联脚本标签的页面时,美丽汤都会对内容进行编码,但最终并没有解码回来。

这是我使用的代码:

代码语言:javascript
运行
复制
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() )

我想要这个输出:

代码语言:javascript
运行
复制
<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>

但是我得到了这个输出:

代码语言:javascript
运行
复制
<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>
EN

回答 2

Stack Overflow用户

发布于 2012-12-03 02:37:19

您可能想尝试一下lxml

代码语言:javascript
运行
复制
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))

收益率

代码语言:javascript
运行
复制
<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>
票数 1
EN

Stack Overflow用户

发布于 2012-12-03 02:23:29

你可以这样做:

代码语言:javascript
运行
复制
htmlCodes = (
('&', '&amp;'),
('<', '&lt;'),
('>', '&gt;'),
('"', '&quot;'),
("'", '&#39;'),
)

for i in htmlCodes:
    soup.prettify().replace(i[1], i[0])
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13672216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档