我完全尊重使用 Beautiful Soup 来获取渲染内容,但它可能不是获取页面上渲染内容的理想包。
我在获取渲染内容或典型浏览器中的可见内容时遇到了类似的问题。特别是我有许多可能不典型的案例来处理下面这样一个简单的例子。在这种情况下,不可显示的标签嵌套在样式标签中,并且在我检查过的许多浏览器中不可见。存在其他变体,例如将类标记设置显示定义为无。然后将此类用于 div。
<html>
<title> Title here</title>
<body>
lots of text here <p> <br>
<h1> even headings </h1>
<style type="text/css">
<div > this will not be visible </div>
</style>
</body>
</html>
上面发布的一个解决方案是:
html = Utilities.ReadFile('simple.html')
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
visible_texts = filter(visible, texts)
print(visible_texts)
[u'\n', u'\n', u'\n\n lots of text here ', u' ', u'\n', u' even headings ', u'\n', u' this will not be visible ', u'\n', u'\n']
这个解决方案在很多情况下确实有应用,并且通常可以很好地完成工作,但是在上面发布的 html 中,它保留了未呈现的文本。在搜索了一些解决方案之后,这里出现了 BeautifulSoup get_text does not strip all tags and JavaScript 和 Rendered HTML to plain text using Python
我尝试了这两种解决方案:html2text 和 nltk.clean_html,并对计时结果感到惊讶,因此认为它们值得为后代提供答案。当然,速度很大程度上取决于数据的内容......
@Helge 的一个答案是关于使用所有事物的 nltk。
import nltk
%timeit nltk.clean_html(html)
was returning 153 us per loop
返回带有渲染 html 的字符串非常有效。这个 nltk 模块甚至比 html2text 更快,尽管 html2text 可能更健壮。
betterHTML = html.decode(errors='ignore')
%timeit html2text.html2text(betterHTML)
%3.09 ms per loop