从字符串中删除html图像标记及其间的所有内容

时间:2012-05-07 17:01:22

标签: python html regex beautifulsoup

我已经看到了一些关于从字符串中删除HTML标记的问题,但我仍然不清楚应该如何处理我的具体案例。

我看过很多帖子建议不要使用正则表达式来处理HTML,但我怀疑我的案例可能会明智地规避这条规则。

我正在尝试解析PDF文件,并且我已成功设法将每个页面从我的示例PDF文件转换为UTF-32文本字符串。当图像出现时,会插入一个HTML样式的标签,其中包含图像的名称和位置(保存在别处)。

在我的应用程序的另一部分中,我需要摆脱这些图像标记。因为我们处理图片标签,所以我怀疑正确使用正则表达式。

我的问题有两个:

  1. 我应该使用正则表达式删除这些标记,还是应该使用像BeautifulSoup这样的HTML解析模块?
  2. 我应该使用哪个正则表达式或BeautifulSoup结构?换句话说,我该怎么编码?
  3. 为清楚起见,标签的结构为<img src="/path/to/file"/>

    谢谢!

3 个答案:

答案 0 :(得分:11)

我会投票表示在你的情况下使用正则表达式是可以接受的。这样的事情应该有效:

def remove_html_tags(data):
    p = re.compile(r'<.*?>')
    return p.sub('', data)

我在这里找到了这个代码段(http://love-python.blogspot.com/2008/07/strip-html-tags-using-python.html)

编辑:仅删除<img .... />形式的内容的版本:

def remove_img_tags(data):
    p = re.compile(r'<img.*?/>')
    return p.sub('', data)

答案 1 :(得分:3)

由于此文本仅包含 图像标记,因此可以使用正则表达式。但对于其他任何事情,你可能最好使用真正的HTML解析器。幸运的是Python提供了一个!这是非常简单的 - 要完全正常运行,这将需要处理更多的极端情况。 (最值得注意的是,XHTML样式的空标签(以斜杠<... />结尾)在这里处理不正确。)

>>> from HTMLParser import HTMLParser
>>> 
>>> class TagDropper(HTMLParser):
...     def __init__(self, tags_to_drop, *args, **kwargs):
...         HTMLParser.__init__(self, *args, **kwargs)
...     self._text = []
...         self._tags_to_drop = set(tags_to_drop)
...     def clear_text(self):
...         self._text = []
...     def get_text(self):
...         return ''.join(self._text)
...     def handle_starttag(self, tag, attrs):
...         if tag not in self._tags_to_drop:
...             self._text.append(self.get_starttag_text())
...     def handle_endtag(self, tag):
...         self._text.append('</{0}>'.format(tag))
...     def handle_data(self, data):
...         self._text.append(data)
... 
>>> td = TagDropper([])
>>> td.feed('A line of text\nA line of text with an <img url="foo"> tag\nAnother line of text with a <br> tag\n')
>>> print td.get_text()
A line of text
A line of text with an <img url="foo"> tag
Another line of text with a <br> tag

并删除img代码......

>>> td = TagDropper(['img'])
>>> td.feed('A line of text\nA line of text with an <img url="foo"> tag\nAnother line of text with a <br> tag\n')
>>> print td.get_text()
A line of text
A line of text with an  tag
Another line of text with a <br> tag

答案 2 :(得分:0)

我的解决方案是:

def remove_HTML_tag(tag, string):
    string = re.sub(r"<\b(" + tag + r")\b[^>]*>", r"", string)
    return re.sub(r"<\/\b(" + tag + r")\b[^>]*>", r"", string)