从 Python 中的字符串中删除 HTML 标签

目录

Remove the HTML tags from a String in Python

  1. 从 Python 中的字符串中删除 HTML 标签
  2. 使用 xml.etree.ElementTree 从字符串中删除 HTML 标签
  3. 使用 lxml 从字符串中删除 HTML 标签
  4. 使用 BeautifulSoup 从字符串中删除 HTML 标签
  5. 在 Python 中使用 HTMLParser 从字符串中删除 HTML 标签

在 Python 中从字符串中删除 HTML 标签

使用该re.sub()方法从字符串中删除 HTML 标记。

re.sub()方法将通过用空字符串替换它们来删除字符串中的所有 HTML 标记。

main.py
import re html_string = """ <div> <ul> <li>Bobby</li> <li>Hadz</li> <li>Com</li> </ul> </div> """ pattern = re.compile('<.*?>') result = re.sub(pattern, '', html_string) # Bobby # Hadz # Com print(result)

代码示例使用正则表达式从字符串中去除 HTML 标记。

re.sub方法返回一个新字符串该字符串是通过用提供的替换替换模式的出现而获得的。

如果未找到模式,则按原样返回字符串。

我们传递给该方法的第一个参数re.sub()是一个正则表达式。

括号<>匹配 HTML 标记的开始和结束字符。

.匹配除换行符以外的任何字符。

星号*匹配前面字符(任何字符)的 0 次或多次重复。

在限定符后添加问号?使其执行非贪婪或最小匹配。

例如,使用正则表达式<.*?>将只匹配<a>.

总的来说,正则表达式匹配所有开始和结束的 HTML 标签。

使用 xml.etree.ElementTree 从字符串中删除 HTML 标签

您还可以使用
xml.etree.ElementTree
模块从字符串中去除 HTML 标签。

main.py
import xml.etree.ElementTree as ET html_string = """ <div> <ul> <li>Bobby</li> <li>Hadz</li> <li>Com</li> </ul> </div> """ result = ''.join(ET.fromstring(html_string).itertext()) # Bobby # Hadz # Com print(result)

fromstring
方法
从字符串常量解析 XML 部分并返回一个
Element
实例。

itertext

方法创建了一个文本迭代器,我们可以用该方法连接
str.join()

使用 lxml 从字符串中删除 HTML 标签

您还可以使用lxml模块从字符串中去除 HTML 标签。

通过运行以下命令确保安装了模块。

pip install lxml # 👇️ or pip3 pip3 install lxml

现在您可以导入并使用该lxml模块从字符串中去除 HTML 标签。

main.py
from lxml.html import fromstring html_string = """ <div> <ul> <li>Bobby</li> <li>Hadz</li> <li>Com</li> </ul> </div> """ result = fromstring(html_string).text_content() # Bobby # Hadz # Com print(result)

text_content方法从字符串中删除所有标记。

使用 BeautifulSoup 从字符串中删除 HTML 标签

您还可以使用BeautifulSoup4
模块从字符串中删除 HTML 标签。

确保您已安装模块以便能够运行代码示例。

pip install lxml pip install beautifulsoup4 # 👇️ or pip3 pip3 install lxml pip3 install beautifulsoup4

现在您可以导入并使用该BeautifulSoup模块从字符串中去除 HTML 标签。

main.py
from bs4 import BeautifulSoup html_string = """ <div> <ul> <li>Bobby</li> <li>Hadz</li> <li>Com</li> </ul> </div> """ result = BeautifulSoup(html_string, 'lxml').text # Bobby # Hadz # Com print(result)

text对象上的属性返回BeautifulSoup字符串的文本内容,不包括 HTML 标记。

在 Python 中使用 HTMLParser 从字符串中删除 HTML 标签

要从 Python 中的字符串中删除 HTML 标记:

  1. Extend from the HTMLParser class from the html.parser module.
  2. Implement the handle_data method to get the data between the HTML tags.
  3. Store the data in a list on the class instance.
  4. Call the get_data() method on an instance of the class.
main.py
from html.parser import HTMLParser class HTMLTagsRemover(HTMLParser): def __init__(self): super().__init__(convert_charrefs=False) self.reset() self.convert_charrefs = True self.fed = [] def handle_data(self, data): self.fed.append(data) def handle_entityref(self, name): self.fed.append(f'&{name};') def handle_charref(self, name): self.fed.append(f'&#{name};') def get_data(self): return ''.join(self.fed) def remove_html_tags(value): remover = HTMLTagsRemover() remover.feed(value) remover.close() return remover.get_data() html_string = """ <div> <ul> <li>Bobby</li> <li>Hadz</li> <li>Com</li> </ul> </div> """ # Bobby # Hadz # Com print(remove_html_tags(html_string))

The remove_html_tags function takes a string and strips the HTML tags from the
supplied string.

We extended from the HTMLParser class. The code snippet is very similar
to the one used internally
by the django module.

The HTMLParser class is used to find tags and other markup and call handler
functions.

The data between the HTML tags is passed from the parser to the derived class by calling self.handle_data().

When convert_charrefs is set to True, character references automatically get
converted to the corresponding Unicode character.

If convert_charrefs is set to False, character references are passed by
calling the self.handle_entityref() or self.handle_charref() methods.

The get_data() method uses the str.join() method to join the list of strings without a separator.

The str.join method
takes an iterable as an argument and returns a string which is the concatenation
of the strings in the iterable.

The remove_html_tags() function takes a string that contains HTML tags and
returns a new string where all opening and closing HTML tags have been removed.

main.py
def remove_html_tags(value): remover = HTMLTagsRemover() remover.feed(value) remover.close() return remover.get_data() html_string = """ <div> <ul> <li>Bobby</li> <li>Hadz</li> <li>Com</li> </ul> </div> """ # Bobby # Hadz # Com print(remove_html_tags(html_string))

The function instantiates the class and feeds the string containing the html
tags to the parser.

下一步是调用close()实例上的方法来处理任何缓冲数据。

最后,我们调用get_data()实例上的方法将字符串列表连接成一个不包含任何 HTML 标记的字符串。