BeautifulSoup.find的返回值是多少?

pro*_*eek 4 regex beautifulsoup

我跑去获得一些分数值.

score = soup.find('div', attrs={'class' : 'summarycount'})
Run Code Online (Sandbox Code Playgroud)

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

<div class=\"summarycount\">524</div>
Run Code Online (Sandbox Code Playgroud)

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

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

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

Eli*_*sky 11

它返回一个对象,您可以使用该对象进行进一步搜索或使用以下内容提取其内容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
Run Code Online (Sandbox Code Playgroud)

打印:

<class 'BeautifulSoup.Tag'>
[u'524']
Run Code Online (Sandbox Code Playgroud)

这里提供了包含多个示例的完整文档.