我正在尝试剥离HTML文档的特定块,尤其是Javascript(<script></script>
)和内联CSS(<style></style>
)。目前,我正在尝试使用re.sub()
Multiline,但运气不佳。有小费吗?
import re
s = '''<html>
<head>
<title>Some Template</title>
<script type="text/javascript" src="{path to Library}/base.js"></script>
<script type="text/javascript" src="something.js"></script>
<script type="text/javascript" src="simple.js"></script>
</head>
<body>
<script type="text/javascript">
// HelloWorld template
document.write(examples.simple.helloWorld());
</script>
</body>
</html>'''
print(re.sub('<script.*script>', '', s, count=0, flags=re.M))
另外,由于您正在解析和修改HTML,因此建议您使用类似BeautifulSoup的HTML解析器。
如果您只想剥离/删除script
HTML树中的所有标签。您可以使用.decompose()
或.extract()
。
.extract()
将返回提取的标签,而.decompose()
只会销毁它。
from bs4 import BeautifulSoup
soup = BeautifulSoup(s, "html.parser")
for i in soup('script'):
i.decompose()
print(soup)
如评论中所述,您可以对HTML树进行其他修改。您可以参考文档以获取更多信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句