基于bs4的防止xss攻击,过滤script标签
from bs4 import BeautifulSoup @login_required def add_article(request): """ 后台管理的添加书籍视图函数 :param request: :return: """ if request.method == "POST": title = request.POST.get("title") content = request.POST.get("content") # 防止xss攻击,过滤script标签 soup=BeautifulSoup(content,"html.parser") for tag in soup.find_all(): print(tag.name) if tag.name=="script": tag.decompose() # 构建摘要数据,获取标签字符串的文本前150个符号 desc=soup.text[0:150]+"..." models.Article.objects.create(title=title,desc=desc,content=str(soup), user=request.user) return redirect("/cn_backend/") return render(request, "backend/add_article.html")