1

我有一个来自网站的 HTML 字符串。以下是其中存在的部分内容。

<p class="news-body">
<a href="/ci/content/player/45568.html" target="new">Paul Harris,</a> the South African spinner, is to retire at the end of the season, bringing to an end a 14-year first-class career.
</p>
<p class="news-body">
 Harris played 37 Tests for South Africa with his slow-left arm but nearly turned his back on international cricket after a stint as a Kolpak with Warwickshire in 2006. The retirement of Nicky Boje prompted Harris' eventual call-up and he went on to take 103 wickets at 37.87.
</p>
<p class="news-body">
His last Test was in Cape Town against India in January 2011 after which he was dropped for legspinner Imran Tahir. As recently as the start of this season he indicated his intention to compete for a Test place once again.
</p>  </div>
   <!-- body area ends here  -->

我想提取所有存在于<p class="news-body">.

我用过美丽的汤。

from BeautifulSoup import BeautifulSoup
html = #the HTML code you've written above
parsed_html = BeautifulSoup(html)
print parsed_html.body.find('p', attrs={'class':'news-body'}).text

不幸的是,上面只返回第一行,即:

Paul Harris,the South African spinner, is to retire at the end of the season, bringing to an end a 14-year first-class career.

我希望它返回所有文本。

4

1 回答 1

1

find只找到第一个元素。你想要findAll,它将返回一个元素列表。

您可以像这样将他们的文本连接在一起:

text = '\n'.join(element.text for element in soup.findAll('p', ...))

另外,我建议您升级到最新版本的 BeautifulSoup。

于 2013-01-10T07:19:19.263 回答