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

BeaftifulSoup4, Django, Python, HTML, Python 3

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 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 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)

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
Support the author Donate

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

    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()

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

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


Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
14,000.00 руб. - 40,000.00 руб.
Разработчик Qt
Annino, Moscow Oblast, Russia
5,000.00 руб. - 15,000.00 руб.
Moskovskiy, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

Aug. 22, 2019, 11:24 p.m.

Qt - Test 001. Signals and slots

  • Result:47points,
  • Rating points-6
Aug. 21, 2019, 10:23 a.m.
Andrej Ermoshin

C++ - Test 002. Constants

  • Result:58points,
  • Rating points-2
Aug. 21, 2019, 10:15 a.m.
Andrej Ermoshin

C++ - Test 001. The first program and data types

  • Result:86points,
  • Rating points6
Last comments
Aug. 19, 2019, 7:41 a.m.
Andrej Jankovich

это проблема дистрибутива, попробуйте установить через пакетный менеджер snap Суть проблемы: libQt5Core которая лежит в дистрибутиве требует версию glibc >= 2.25 у вас видимо …
Aug. 18, 2019, 6:09 a.m.

cqtdeployer /home/aleks/CQtDeployer/bin/cqtdeployer: /lib/x86_64-linux-gnu/ version `GLIBC_2.25' not found (required by /home/aleks/CQtDeployer/lib/ linux mint …
Aug. 17, 2019, 9:04 a.m.

github ChekableTView Правой групповая смена значения при перетаскивании левой как обычно.
Aug. 16, 2019, 1:03 p.m.
Evgenij Legotskoj

Потому, что в минуте 60 секунд
Aug. 16, 2019, 12:16 p.m.

а почему делитель 60000, а не 1000?
Now discuss on the forum
Aug. 24, 2019, 7:21 a.m.
Evgenij Legotskoj

Не помню, давно уже с QML не работал, по-моему, обычно пишет в консоль, что не находит файл. В любом случае какую-то ошибку в консоль выкидывает. Но если честно, если у вас проект будет ак…
Aug. 24, 2019, 4:27 a.m.
Brjus Gliff

Спасибо, вначале в документации было не понятно что к чему, теперь разобрался
Aug. 21, 2019, 8:36 a.m.

Александр, мне не нужно перебирать. Вы говорите правильно, сначала я написал избыточный код просто не подумав. Задача такая, мне нужно просто переложить из QMap в атрибуты xml тега все, что там …
Aug. 21, 2019, 3:16 a.m.

Если Вы разрабатываете какую-то универсальную утилиту, которая вообще не привязана к логике, тогда как вариант: 1. Получить список таблиц через QSqlDatabase::tables 2. Для каждой табли…
© EVILEG 2015-2019
Recommend hosting TIMEWEB