Python Convert Link Text To Html

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

Code.

import bleachstr = 'www.google.com or https://gohugo.io/hosting-and-deployment/hosting-on-github/'html = bleach.linkify(str)print(html)

Output.

<a href="http://www.google.com" rel="nofollow">www.google.com</a> or <a href="https://gohugo.io/hosting-and-deployment/hosting-on-github/" rel="nofollow">https://gohugo.io/hosting-and-deployment/hosting-on-github/</a>

You can also use bleach to sanitize or escape html.

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

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=[])print(html)

Output.

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

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.