Beautifulsoup获取标签内容的最简单方法

时间:2015-04-16 23:01:06

标签: python html beautifulsoup bs4

问题是Beautifulsoup标签的contents是一个列表而不是字符串。因此,我必须使用for循环来获取标记内的内容。这很麻烦。有没有更好的方法呢?

from bs4 import BeautifulSoup
html_doc = u'<li><span class="def">1. <span class="cat">cat</span>example<span class="ex">ex</span></span></li>'
soup = BeautifulSoup(html_doc)
div = soup.find("span", class_='def')
print div.contents
result = ''
for divcont in div.contents:
    result = result + unicode(divcont)
print result

输出:

[u'1. ', <span class="cat">cat</span>, u'example', <span class="ex">ex</span>]
1. <span class="cat">cat</span>example<span class="ex">ex</span>

字符串1. <span class="cat">cat</span>example<span class="ex">ex</span>是我想要的,但我需要一个更简单的方法来获取它。

1 个答案:

答案 0 :(得分:0)

使用join

from bs4 import BeautifulSoup
html_doc = u'<li><span class="def">1. <span class="cat">cat</span>example<span class="ex">ex</span></span></li>'
soup = BeautifulSoup(html_doc)
div = soup.find("span", class_='def')
print(''.join(str(e) for e in div))