Evgenii Legotckoi
Evgenii LegotckoiOct. 24, 2018, 2:38 a.m.

Django - Tutorial 038. Use BeatifulSoup 4 to clean up the published content from unwanted html tags


When developing a web site that adds the ability to write comments or publish articles that allow html layout, the mechanism for clearing unwanted html tags, in particular script and style tags, is important, since malicious scripts on a quality resource definitely should not be present. It will also be good to be able to clean up the style of the text, especially if the resource implies a uniform style. The discordance of screaming fonts is not needed by anyone, and adds problems with the layout.

To implement this mechanism, I use the Python package Beautiful Soup 4 and finally wrote one class, which essentially does everything I need. Removes unnecessary tags, adds necessary classes to tags, saves classes in tags, if you need to leave them during stripping, this is important for classes that are added at the stage of writing a comment, for example, when inserting a YouTube video or adding program code when the user selects which programming language should be represented in the program code block.

Install BeautifulSoup 4

pip install beautifulsoup4

Program code

This example is presented in the form of a class, so that using the inheritance and redefinition of the cleaning method to form the necessary logic, and the program code of the module for cleaning html does not turn into a collection of heterogeneous, inconsistent functions.

# -*- coding: utf-8 -*-

import re

from bs4 import BeautifulSoup
from YourDjangoApp import settings

class ESoup:
    # initialization of the text clear object,
    # can use immediately receive additional tags for deletion so as not to override the class
    def __init__(self, text, tags_for_extracting=()):
        self.soup = BeautifulSoup(text, "lxml") if text else None
        self.tags_for_extracting = ('script', 'style',) + tags_for_extracting

    # Method to remove specified tags
    def __extract_tags(self, soup, tags=()):
        for tag in tags:
            for current_tag in soup.find_all(tag):
        return soup

    # Method for deleting attributes of all tags
    def __remove_attrs(self, soup):
        for tag in soup.find_all(True):
            tag.attrs = {}
        return soup

    # Method for deleting attributes of all tags except those listed in whitelist_tags
    def __remove_all_attrs_except(self, soup, whitelist_tags=()):
        for tag in soup.find_all(True):
            if tag.name not in whitelist_tags:
                tag.attrs = {}
        return soup

    # Remove all attributes from all tags except those listed in whitelist_tags
    # If the tag is in whitelist_tags, it will only delete those attributes that are not listed in whitelist_attrs
    # Also, this method saves to the tag the classes listed in whitelist_classes
    # regardless of whether it was listed in whitelist_tags or in whitelist_attrs.
    # I just have classes with a special position for tags
    def __remove_all_attrs_except_saving(self, soup, whitelist_tags=(), whitelist_attrs=(), whitelist_classes=()):
        for tag in soup.find_all(True):
            saved_classes = []
            if tag.has_attr('class'):
                classes = tag['class']
                for class_str in whitelist_classes:
                    if class_str in classes:

            if tag.name not in whitelist_tags:
                tag.attrs = {}
                attrs = dict(tag.attrs)
                for attr in attrs:
                    if attr not in whitelist_attrs:
                        del tag.attrs[attr]

            if len(saved_classes) > 0:
                tag['class'] = ' '.join(saved_classes)

        return soup

    # Adds a nofollow relationship to the tag, checking the url of the src or img attribute
    # If the link leads to the internal pages of your site, then nofollow will not be added.
    def __add_rel_attr(self, soup, tag, attr):
        for tag in soup.find_all(tag):
            attr_content = tag.get(attr)
            if not attr_content.startswith(settings.SITE_URL) and not attr_content.startswith('/'):
                tag['rel'] = ['nofollow']
        return soup

    # Adds new classes to the tag, preserving those classes that already existed.
    def __add_class_attr(self, soup, tag, classes=()):
        for tag in soup.find_all(tag):
            saved_classes = []
            if tag.has_attr('class'):
            tag['class'] = ' '.join(saved_classes)
        return soup

    # The method that performs the cleaning, I propose to override it, if you need to change the logic for cleaning up the html code
    def clean(self):
        # if BeautifulSoup was created during initialization, then you can perform the cleanup
        if self.soup:
            # Remove all tags that we don’t like.
            soup = self.__extract_tags(soup=self.soup, tags=self.tags_for_extracting)
            # Remove all attributes from all tags except
            # src and href for tags img and a,
            # and also leave prettyprint class
            soup = self.__remove_all_attrs_except_saving(
                whitelist_tags=('img', 'a'),
                whitelist_attrs=('src', 'href',),
            # add rel="nofollow" for external links
            soup = self.__add_rel_attr(soup=soup, tag='a', attr='href')
            soup = self.__add_rel_attr(soup=soup, tag='img', attr='src')
            # improve the appearance of images using the img-fluid class
            soup = self.__add_class_attr(soup=soup, tag='img', classes=('img-fluid',))
            # add the linenums class for pre tags
            soup = self.__add_class_attr(soup=soup, tag='pre', classes=('linenums',))
            # returning useful content, the fact is that BeautifulSoup 4 adds more html and body tags,
            # which I, for example, do not need
            return re.sub('<body>|</body>', '', soup.body.prettify())
        return ''

    # Static class method, something like Shortcut
    def clean_text(text, tags_for_extracting=()):
        soup = ESoup(text=text, tags_for_extracting=tags_for_extracting)
        return soup.clean()



soup = ESoup(text=text, tags_for_extracting=tags_for_extracting)

Or so

ESoup.clean_text(text=text, tags_for_extracting=tags_for_extracting)
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Илья Чичак
  • Dec. 4, 2018, 9:37 p.m.

я думаю, что последний

    def clean_text(text, tags_for_extracting=()):
        soup = ESoup(text=text, tags_for_extracting=tags_for_extracting)
        return soup.clean()

есть смысл заменить на classmethod (при наследовании, старый вариант сломается, а с классом - нет):

    def clean_text(cls, text, tags_for_extracting=()):
        soup = cls(text=text, tags_for_extracting=tags_for_extracting)
        return soup.clean()
Evgenii Legotckoi
  • Dec. 5, 2018, 4:34 a.m.

Спасибо за информацию, не думал об этом.

Надо будет проверить на кошках.


Only authorized users can post comments.
Please, Log in or Sign up

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:30points,
  • Rating points-10

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4

C++ - Test 005. Structures and Classes

  • Result:50points,
  • Rating points-4
Last comments
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCTDec. 27, 2023, 8:57 a.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
ДмитрийJan. 10, 2024, 4:18 a.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 6:48 a.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks