Skip to main content
 首页 » 编程设计

python之提取 HTML 页面中的所有 <script> 标签并附加到文档底部

2025年05月04日18me-sa

谁能告诉我如何提取和删除所有 <script> HTML 文档中的标记并将它们添加到文档末尾,就在 </body></html> 之前?我想尝试避免使用 lxml请。

谢谢。

请您参考如下方法:

答案很简单,可能会漏掉很多细微差别。然而,这应该让您了解如何着手去做,并从总体上改进它。我相信这可以改进,但您应该能够在文档的帮助下快速完成。

引用文档:http://www.crummy.com/software/BeautifulSoup/documentation.html

from bs4 import BeautifulSoup 
 
doc = ['<html><script type="text/javascript">document.write("Hello World!")', 
       '</script><head><title>Page title</title></head>', 
       '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', 
       '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', 
       '</html>'] 
soup = BeautifulSoup(''.join(doc)) 
 
 
for tag in soup.findAll('script'): 
    # Use extract to remove the tag 
    tag.extract() 
    # use simple insert 
    soup.body.insert(len(soup.body.contents), tag) 
 
print soup.prettify() 

输出:

<html> 
 <head> 
  <title> 
   Page title 
  </title> 
 </head> 
 <body> 
  <p id="firstpara" align="center"> 
   This is paragraph 
   <b> 
    one 
   </b> 
   . 
  </p> 
  <p id="secondpara" align="blah"> 
   This is paragraph 
   <b> 
    two 
   </b> 
   . 
  </p> 
  <script type="text/javascript"> 
   document.write("Hello World!") 
  </script> 
 </body> 
</html>