【问题标题】:Extract all <script> tags in an HTML page and append to the bottom of the document提取 HTML 页面中的所有 <script> 标记并附加到文档底部
【发布时间】:2018-01-27 03:12:46
【问题描述】:

谁能告诉我如何提取和删除 HTML 文档中的所有 &lt;script&gt; 标记并将它们添加到文档的末尾,就在 &lt;/body&gt;&lt;/html&gt; 之前?我想尽量避免使用lxml

谢谢。

【问题讨论】:

  • 当你使用它时,让它们异步加载。将带来更大的性能优势。

标签: python beautifulsoup


【解决方案1】:

答案很简单,可能会忽略许多细微差别。但是,这应该让您了解如何去做,总体上改进它。我相信这可以改进,但您应该能够在文档的帮助下快速做到这一点。

参考文档: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>

【讨论】:

    猜你喜欢
    • 2016-03-28
    • 2022-01-23
    • 1970-01-01
    • 2021-04-10
    • 2022-01-06
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2013-07-03
    相关资源
    最近更新 更多