tgr*_*ray 25
您可以将BeautifulSoup与此(和其他)方法一起使用:
soup = BeautifulSoup(source.lower())
to_extract = soup.findAll('script')
for item in to_extract:
item.extract()
Run Code Online (Sandbox Code Playgroud)
这实际上从HTML中删除了节点.如果你想留下空<script></script>标签,你将不得不使用item属性而不是从汤中提取它.
你想阻止XSS吗?只是删除<script>标签不会解决所有可能的攻击!这里列出了很多可能容易受到攻击的方法(其中一些很有创意)http://ha.ckers.org/xss.html.阅读本页后,您应该明白为什么只<script>使用正则表达式来删除标记不够健壮.python库lxml有一个功能,可以强大地清理HTML,使其安全显示.
如果您确定要删除<script>标记,则lxml中的代码应该可以正常工作:
from lxml.html import parse
root = parse(filename_or_url).getroot()
for element in root.iter("script"):
element.drop_tree()
Run Code Online (Sandbox Code Playgroud)
注意:我使用常规表达式对所有解决方案进行了投票.看看为什么你不应该使用正则表达式解析HTML:使用正则表达式来解析HTML:为什么不呢?
注2:另一个SO问题显示HTML无法用正则表达式解析:你能提供一些例子,说明为什么难以用正则表达式解析XML和HTML吗?
您可以使用HTMLParser模块(复杂)或使用正则表达式来执行此操作:
import re
content = "asdf <script> bla </script> end"
x=re.search("<script>.*?</script>", content, re.DOTALL)
span = x.span() # gives (5, 27)
stripped_content = content[:span[0]] + content[span[1]:]
Run Code Online (Sandbox Code Playgroud)
编辑:re.DOTALL,感谢 tgray