从字符串中删除 HTML 标签的 Python 代码 [英] Python code to remove HTML tags from a string

查看:37
本文介绍了从字符串中删除 HTML 标签的 Python 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的文字:

text = """<div>
<h1>Title</h1>
<p>A long text........ </p>
<a href=""> a link </a>
</div>"""
<h1>标题</h1><p>一个长文本........ </p><a href="">链接</div>"""

using pure Python, with no external module I want to have this:

使用纯 Python,没有我想要的外部模块:

>>> print remove_tags(text) Title A long text..... a link

我知道我可以使用 lxml.html.fromstring(text).text_content() 来做到这一点,但我需要在纯 Python 中使用 2.6+ 的内置库或标准库来实现相同的效果

I know I can do it using lxml.html.fromstring(text).text_content() but I need to achieve the same in pure Python using builtin or std library for 2.6+

我该怎么做?

推荐答案

使用正则表达式

使用正则表达式,你可以清理<>中的所有内容:

import re
# as per recommendation from @freylis, compile once only
CLEANR = re.compile('<.*?>') 

def cleanhtml(raw_html):
  cleantext = re.sub(CLEANR, '', raw_html)
  return cleantext

某些 HTML 文本还可以包含未括在括号中的实体,例如&nsbm".如果是这种情况,那么您可能希望将正则表达式编写为

Some HTML texts can also contain entities that are not enclosed in brackets, such as '&nsbm'. If that is the case, then you might want to write the regex as

CLEANR = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')

链接包含有关此的更多详细信息.

This link contains more details on this.

您也可以使用 BeautifulSoup 附加包来查找所有原始文本.

You could also use BeautifulSoup additional package to find out all the raw text.

调用 BeautifulSoup 时需要显式设置解析器我推荐在替代答案中提到的 "lxml"(比默认的(html.parser)强得多(即无需额外安装即可使用).

You will need to explicitly set a parser when calling BeautifulSoup I recommend "lxml" as mentioned in alternative answers (much more robust than the default one (html.parser) (i.e. available without additional install).

from bs4 import BeautifulSoup
cleantext = BeautifulSoup(raw_html, "lxml").text

但这并不妨碍您使用外部库,因此我推荐第一种解决方案.

But it doesn't prevent you from using external libraries, so I recommend the first solution.

要使用 lxml,您需要 pip install lxml.

这篇关于从字符串中删除 HTML 标签的 Python 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆