Python Convert Link Text To Html

December 19, 2017
Use bleach

Install bleach.

Bleach is an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes.

Bleach can also linkify text safely, applying filters that Django’s urlize filter cannot, and optionally setting rel attributes, even on links already in the text.

pip install bleach


import bleach

str = ' or'
html = bleach.linkify(str)


<a href="" rel="nofollow"></a> or <a href="" rel="nofollow"></a>

You can also use bleach to sanitize or escape html.

str = '<script>danger()</script> <strong>bold</strong>'
html = bleach.clean(str)

Output. Notice script tag is escaped but strong tag remained.

&lt;script&gt;danger()&lt;/script&gt; <strong>bold</strong>

If you want to escape all HTML tags, use:

str = '<script>danger()</script> <strong>bold</strong>'
html = bleach.clean(str, tags=[])


\&lt;script&gt;danger()&lt;/script&gt; &lt;strong&gt;bold&lt;/strong&gt;

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.