答案很简单,可能会遗漏很多细微差别。无论如何,这应该给你一个如何去做的想法,总体上改善它。我相信这是可以改进的,但是您应该能够在文档的帮助下快速地做到这一点。
参考文档:
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>