【发布时间】:2014-12-02 20:01:56
【问题描述】:
我有从 MS Word 保存的 html 文档,现在它有一些与 MS Word 相关的标签。我不需要保持任何向后兼容性,我只需要从该文件中提取内容。问题是单词特定标签并没有那么容易删除。
我有这个代码:
from bs4 import BeautifulSoup, NavigableString
def strip_tags(html, invalid_tags):
soup = BeautifulSoup(html)
for tag in soup.findAll(True):
if tag.name in invalid_tags:
s = ""
for c in tag.contents:
if not isinstance(c, NavigableString):
c = strip_tags(unicode(c), invalid_tags)
s += unicode(c)
tag.replaceWith(s)
return soup
它会删除不需要的标签。但是即使使用了这种方法,也会留下一些。 例如看这个:
<P class="MsoNormal"><SPAN style="mso-bidi-font-weight: bold;">Some text -
some content<o:p></o:p></SPAN></P>
<P class="MsoNormal"><SPAN style="mso-bidi-font-weight: bold;">some text2 -
647894654<o:p></o:p></SPAN></P>
<P class="MsoNormal"><SPAN style="mso-bidi-font-weight: bold;">some text3 -
some content blabla<o:p></o:p></SPAN></P>
这是它在 html 文档中的外观。当我使用这样的方法时:
invalid_tags = ['span']
stripped = strip_tags(html_file, invalid)
print stripped
打印如下:
<p class="MsoNormal">Some text -
some content<html><body><o:p></o:p></body></html></p>
<p class="MsoNormal">some text2 -
647894654<html><body><o:p></o:p></body></html></p>
<p class="MsoNormal">some text3 -
some content blabla<html><body><o:p></o:p></body></html></p>
正如您所见,出于某种原因,html 和 body 标记出现在那里,即使在 html 中它不存在。如果我添加invalid_tags = ['span', 'o:p'],它会删除<o:p></o:p> 标签,但如果我添加删除html 或body 标签,它不会做任何事情,它仍然保留在那里。
附:如果我直接更改查找标签的位置,我可以在那里删除html 标签。例如,通过在方法中添加这一行(在使用 findAll 之前)soup = soup.body。但在此之后,body 标签仍然挂在那些特定的段落中。
【问题讨论】:
标签: python html tags beautifulsoup