【发布时间】:2016-06-14 20:32:38
【问题描述】:
我正在尝试去除特定的 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))
【问题讨论】:
-
你为什么不去
BeautifulSoup? -
@JasonEstibeiro 我对 BeautifulSoup 的了解并不广泛,但我所有的用途都是解析 HTML 和提取内容。我只想清除其中的一部分,并将其他部分(如粗体和斜体标签)转换为不同的标记。我不知道 BS4 能够做到这一点。
-
好吧,您可以清除部分 HTML。看看这个answer。
-
您甚至可以通过更改其标记名称和/或属性来修改 HTML 树。看看doc。
-
@JasonEstibeiro 嗯...我会的。把它放在答案中,功劳归你所有。
标签: python html regex python-3.x