什么是最简单的方法来逃避html标签,除了一些类似的Bold,

时间:2015-12-06 23:41:34

标签: python html django

我需要使用pythonic模块/算法来逃避确定的html标签,例如,假设我们有以下html代码:

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

我们希望转换为:

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

出现在类似下面的html页面中:

&LT; I&gt;这&LT; I&GT /;是一个示例

我怎样才能以最简单的方式做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用Beautiful Soup

快速举例:

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

相反,您可以从计算机中打开html文件以避免使用那个丑陋的字符串。

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>

然后:

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

在您的情况下,您搜索'b'标签或'i'标签,但适用相同的逻辑。 该文档进一步介绍了如何使用此库。 我希望这对你有用。干杯!