BeautifulSoup.find的返回值是多少?

时间:2010-04-15 17:09:36

标签: regex beautifulsoup

我跑去获得分数值。

score = soup.find('div', attrs={'class' : 'summarycount'})

我运行'打印分数'得到如下。

<div class=\"summarycount\">524</div>

我需要提取数字部分。我使用了re模块但失败了。

m = re.search("[^\d]+(\d+)", score)
TypeError: expected string or buffer

function search in re.py at line 142
return _compile(pattern, flags).search(string)
  • 查找功能的返回类型是什么?
  • 如何从得分变量中获取数字?
  • 有没有简单的方法让BeautifulSoup返回值(在本例中为524)本身?

1 个答案:

答案 0 :(得分:10)

它返回一个对象,您可以使用该对象进行进一步搜索或使用score.contents提取其内容:

from BeautifulSoup import BeautifulSoup

str = r'''
    <body>
    <div class="summarycount">524</div>
    <div class="foo">111</div>
    </body>
'''

soup = BeautifulSoup(str)
score = soup.find('div', attrs={'class' : 'summarycount'})

print type(score)
print score.contents

打印:

<class 'BeautifulSoup.Tag'>
[u'524']

包含多个示例的完整文档是available here

相关问题