M.javid
M.javid

Reputation: 6647

What is easiest way to escape html tags, except some of those similar Bold,

I need using a pythonic module/algorithm to escape only determined html tags, for example, suppose we have below html code:

<i>This</i> is an <b>example</b>

And we want convert to:

&lt;i&gt;This&lt;/i&gt; is an <b>example</b>

to present in html page similar below:

<i>This</i> is an example

How can i doing this, in easiest way?

Upvotes: 1

Views: 964

Answers (1)

pazitos10
pazitos10

Reputation: 1709

You can use Beautiful Soup

Quick example:

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

Instead, you can open the html file from your computer to avoid that ugly string.

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

print(soup.prettify())
# <html>
#  <head>
#   <title>
#    The Dormouse's story
#   </title>
#  </head>
#  <body>
#   <p class="title">
#    <b>
#     The Dormouse's story
#    </b>
#   </p>
#   <p class="story">
#    Once upon a time there were three little sisters; and their names were
#    <a class="sister" href="http://example.com/elsie" id="link1">
#     Elsie
#    </a>
#    ,
#    <a class="sister" href="http://example.com/lacie" id="link2">
#     Lacie
#    </a>
#    and
#    <a class="sister" href="http://example.com/tillie" id="link2">
#     Tillie
#    </a>
#    ; and they lived at the bottom of a well.
#   </p>
#   <p class="story">
#    ...
#   </p>
#  </body>
# </html>

And then:

for link in soup.find_all('a'):
    print(link.get('href'))
# http://example.com/elsie
# http://example.com/lacie
# http://example.com/tillie

In your case, you search for a 'b' tag or an 'i' tag, but the same logic applies. The documentation goes further in how to use this library. I hope this will be useful to you. Cheers!

Upvotes: 1

Related Questions