提取HTML页面中的所有<script>标签并添加到文档底部
有人能告诉我怎么把HTML文档里的所有<script>
标签提取出来,并把它们放到文档的最后,紧挨着</body></html>
之前吗?我想尽量不使用lxml
这个库。
谢谢。
1 个回答
6
这个答案很简单,可能会遗漏一些细节。不过,这应该能给你一个大概的思路,帮助你去做这件事,整体上也能有所提升。我相信这个方法可以进一步改进,但你可以通过查阅文档来快速做到这一点。
参考文档: 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>