有没有方法从HTML文档中删除javascript代码?

时间:2011-11-27 05:51:21

标签: javascript python html

我想从HTML文档中删除所有javascript代码,并保留实际文本。是否有任何正则表达式或python脚本来执行此操作?感谢。

3 个答案:

答案 0 :(得分:5)

使用BeautifulSoup

#!/usr/bin/env python
from BeautifulSoup import BeautifulSoup

with open("with-scripts.html", "r") as f:
    soup = BeautifulSoup(f.read())

for script in soup("script"):
    script.extract()

with open("without-scripts.html", "w") as f:
    f.write(soup.prettify())

答案 1 :(得分:1)

你可以写一个正则表达式来寻找'<script''script>',并且非常好。

编辑:正如@cHao所指出的那样 - Regex's are bad for parsing HTML

在您完全控制HTML的地方,正则表达式可能仍然有用。

答案 2 :(得分:0)

您可以使用此jQuery代码删除:

$(javascript).html('')

和Firebug将jQuery代码注入网页:

>>> var x = window.open(""); 
Window opened 
>>> x 
Window about:blank 
>>> x.document 
Document about:blank 
>>> x.document.write("$(javascript).html('')"); 
Alert popped up