bs4的简单应用之防止xss攻击和文本截断

BeautifulSoup可以过滤html标签,根据这个功能我们可以防止xss攻击和进行文本过滤

1. 安装

pip install beautifulsoup4

2.导入、使用

from bs4 import BeautifulSoup

@login_required
def add_article(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')

        soup = BeautifulSoup(content, 'html.parser')
        # 过滤script,防止xss攻击
        for tag in soup.find_all():
            if tag.name == 'script':
                tag.decompose()

        # 获取文本进行截取,赋值给desc字段
        desc = soup.text[0:150] + '...'

        models.Article.objects.filter(user=request.user).create(
            title=title,
            user=request.user,
            desc=desc,
            content=str(soup)
        )

        return redirect(reverse('blog:backend'))

    return render(request, 'backend/add_article.html')
posted @ 2019-02-20 09:47  梁少华  阅读(340)  评论(0编辑  收藏  举报