【问题标题】:Delete HTML Tags from string Python从字符串 Python 中删除 HTML 标签
【发布时间】:2014-12-28 13:45:26
【问题描述】:

我正在使用 feedparser 开发一个脚本(用于提取 RSS 提要)。 使用一些函数,我最终得到了一个名为 description 的字符串,如下所示:

"This is the description of the feed. < img alt='' height='1' src='http://linkOfARandomImage.of/the/feed' width='1' />"

html标签可以变化,我可以有img,a href,“p”,“h1”,......而且数量也可能不同。所以它们是相当随机的。但我想做的只是保留第一个文本。 我想知道是否有办法删除所有标签,我正在考虑做类似的事情:从这个字符“

【问题讨论】:

标签: python html tags feedparser


【解决方案1】:

删除所有标签:

import re
text = "This is the description of <img alt='' height='1' src='http://linkOfARandomImage.of/the/feed' width='1' /> the <br> text"
text = re.sub("<.*?>", "", text)
#text = "This is the description of  the  text"

删除不必要的空格:

text = re.sub("\w*", " ", text)

编辑:

text = re.sub("\w+", " ", text)

【讨论】:

  • 谢谢,这就是我要找的!
  • 正确,但请注意,使用正则表达式解析 HTML 通常不是一个好习惯。有解析器。这并不是要使您的答案无效,只是要指出 OP 的注意力可能不会被推断为“我如何解析 HTML?使用正则表达式!”
  • 是的,\w* 匹配零个或多个单词字符。
  • Jivan,这不完全是一个 html 文件,它是一个 RSS,我使用 FeedParser 将其废弃,但给出的功能并不能完全符合我的要求,因此我需要对其进行一些更改。
【解决方案2】:

如果您只想删除第一个文本(在任何标记出现之前),则无需使用正则表达式。

只需使用splitstrip

>>> html = "Some text here <tag>blabla</tag> <other>hey you</other>"
>>> text = html.split("<")[0].strip()
>>> text
"Some text here"

split在遇到指定字符时,将html字符串截断。

strip 删除结果字符串开头和结尾的所有空格。

警告:仅当您要保留的文本中没有任何&lt; 时才有效。

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2019-01-06
    相关资源
    最近更新 更多