提取div的内容?

时间:2013-06-25 11:36:51

标签: python html beautifulsoup

如何在bs4中提取div的内容:

>>> Doc
<div class="document">
<p>Text.</p>
<p>More text</p>
</div>

>>> type(Doc)
bs4.element.Tag

我希望得到

<p>Text.</p>
<p>More text</p>

2 个答案:

答案 0 :(得分:1)

使用.contents

>>> Doc = soup.find('div', {'class': 'document'}) # assuming soup is your main content
>>> for i in [x for x in Doc.contents if x != '\n']:
...     print i
... 
<p>Text.</p>
<p>More text</p>

答案 1 :(得分:0)

要获得div的全部内容,无论其中包含哪些元素,请使用soup.find("div").prettify()来有效地获取内部HTML。