1
我有從MS Word保存的html文檔,現在它有一些與MS Word相關的標籤。我不需要保持向後兼容性,我只需要從該文件中提取內容。問題在於特定於文字的標籤不會輕易刪除。BeautifulSoup - 刪除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標記,則它不會執行任何操作,並且它仍保留在那裏。
P.S.如果我直接更改要查找標籤的位置,我可以在那裏刪除html
標籤。例如,通過在方法中添加此行(在使用findAll
之前)soup = soup.body
。但在此之後,body
標籤仍被懸掛在這些特定段落中。
誰能告訴我爲什麼在我的Python代碼中看不到語法高亮? – xcaptain 2014-10-08 08:39:21
它做同樣的事情。 – Andrius 2014-10-08 08:40:19
我不知道你的目的是什麼。當我用你的html執行strip_tags(html,['span','o:p'])時,我可以去掉這些標籤。 – xcaptain 2014-10-08 08:49:55