我有从msword保存的html文档,现在它有一些与msword相关的标签。我不需要保持任何向后兼容,我只需要从文件中提取内容。问题是,特定于单词的标记不容易删除。在
我有这个代码: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
它删除不需要的标记。但有些人甚至在使用这种方法后仍会留下。
例如,看看这个:
^{pr2}$
这就是它在html文档中的外观。当我使用这样的方法时:invalid_tags = ['span']
stripped = strip_tags(html_file, invalid)
print stripped
它是这样打印的:
Some text -
some content<html><body><o:p></o:p></body></html>
some text2 -
647894654<html><body><o:p></o:p></body></html>
some text3 -
some content blabla<html><body><o:p></o:p></body></html>
正如您所看到的,由于某些原因,html和{}标记出现在那里,即使在html中它并不存在。如果我添加invalid_tags = ['span', 'o:p'],它会删除
另外,如果我直接更改查找标记的位置,我可以在那里删除html标记。例如,在方法中添加这一行(在使用findAll之前)soup = soup.body。但在这之后,body标记仍然挂在那些特定的段落中。在