提取所有 <script>HTML 页面中的标签并附加到文档的底部 [英] Extract all <script> tags in an HTML page and append to the bottom of the document
本文介绍了提取所有 <script>HTML 页面中的标签并附加到文档的底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我如何提取和删除 HTML 文档中的所有 <script>
标签,并将它们添加到文档的末尾,就在 </正文></html>
?我想尽量避免使用 lxml
.
Could someone tell me how I can extract and remove all the <script>
tags in a HTML document and add them to the end of the document, right before the </body></html>
? I'd like to try and avoid using lxml
please.
谢谢.
推荐答案
答案很简单,可能会遗漏许多细微差别.然而,这应该让你知道如何去做,总体上改进它.我相信这可以改进,但您应该能够在文档的帮助下快速完成.
The answer is simple and may miss many nuances. How ever, this should give you an idea of how to go about doing it, improving it in general. I am sure this can be improved but you should be able to do that quickly with help of the documentation.
参考文档:http://www.crummy.com/software/BeautifulSoup/文档.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>
这篇关于提取所有 <script>HTML 页面中的标签并附加到文档的底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文