【发布时间】:2012-10-31 12:16:41
【问题描述】:
我正在尝试使用 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>
我尝试做类似的事情:
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)
...但是这样我的 span 元素总是在一个新的行上。这当然是一个简单的例子。有没有办法在 Python 中获取 HTML 页面中的文本,就像它在浏览器中呈现的方式一样(不需要 css 规则,只需常规方式 div、span、li 等元素呈现)?
【问题讨论】:
-
向我们展示预期的输出是什么样的?你想去掉所有的缩进空格和换行符,对吧?
标签: python beautifulsoup