bta*_*rov 37 python beautifulsoup
我正在尝试使用BeautifulSoup转换一大块HTML文本.这是一个例子:
<div>
<p>
Some text
<span>more text</span>
even more text
</p>
<ul>
<li>list item</li>
<li>yet another list item</li>
</ul>
</div>
<p>Some other text</p>
<ul>
<li>list item</li>
<li>yet another list item</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
我尝试过这样的事情:
def parse_text(contents_string)
Newlines = re.compile(r'[\r\n]\s+')
bs = BeautifulSoup.BeautifulSoup(contents_string, convertEntities=BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
txt = bs.getText('\n')
return Newlines.sub('\n', txt)
Run Code Online (Sandbox Code Playgroud)
...但是那样我的span元素总是在新的一行上.这当然是一个简单的例子.有没有办法让HTML页面中的文本在浏览器中呈现的方式(不需要css规则,只有常规的div,span,li等元素呈现)?
del*_*del 84
BeautifulSoup是一个抓取库,因此它可能不是进行HTML渲染的最佳选择.如果使用BeautifulSoup不是必需的,你应该看看html2text.例如:
import html2text
html = open("foobar.html").read()
print html2text.html2text(html)
Run Code Online (Sandbox Code Playgroud)
这输出:
Some text more text even more text * list item * yet another list item Some other text * list item * yet another list item
我在尝试解析呈现的 HTML 时遇到了同样的问题。基本上,BS 似乎不是这方面的理想方案。@Del 提供了很棒的 html2text 解决方案。
在一个不同的 SO 问题上:BeautifulSoup get_text 并没有 去除使用 nltk 提到的所有标签和 JavaScript @Helge。不幸的是 nltk 似乎停止了这种方法。
我尝试了 html2text 和 nltk.clean_html 并且对计时结果感到惊讶,因此认为它们值得后人回答。当然,速度在很大程度上取决于数据的内容......
来自@Helge (nltk) 的回答。
import nltk
%timeit nltk.clean_html(html)
was returning 153 us per loop
Run Code Online (Sandbox Code Playgroud)
返回带有渲染 html 的字符串非常有效。这个 nltk 模块甚至比 html2text 还要快,尽管 html2text 可能更健壮。
上面来自@del的回答
betterHTML = html.decode(errors='ignore')
%timeit html2text.html2text(betterHTML)
%3.09 ms per loop
Run Code Online (Sandbox Code Playgroud)