如何使用beautifulsoup获取一个嵌套在另一个标签中的span标签内的文本?

3
我该如何获取所有class为“no-wrap text-right circulating-supply”的标签的值?我使用的方法是:
text=[ ]

text=(soup.find_all(class_="no-wrap text-right circulating-supply"))
< p > text [0] 的输出:

'\n\n17,210,662\nBTC\n'

我只想提取数字值。
一个示例实例:
```html

我只想提取数字值。

一个示例实例:

```
<td class="no-wrap text-right circulating-supply" data-sort="17210662.0">
            <span data-supply="17210662.0">
             <span data-supply-container="">
              17,210,662
             </span>
             <span class="hidden-xs">
              BTC
             </span>
            </span>
           </td>

感谢您的选择。
2个回答

2
如果所有元素具有相似的HTML结构,请尝试以下方法以获取所需输出:
texts = [node.text.strip().split('\n')[0] for node in soup.find_all(class_="no-wrap text-right circulating-supply")]

我遇到了这个错误TypeError: 'NoneType' object is not callable - srijan srivastav
你确定 text[0] 会返回文本吗?我猜 soup.find_all() 应该会返回类似于 WebElement 对象的东西。请检查更新后的答案。 - Andersson
你说得对,我忘记加 .text 了。 这样就可以了。 非常感谢! - srijan srivastav

1
这可能看起来有些过度,您可以使用正则表达式提取数字。
from bs4 import BeautifulSoup
html = """<td class="no-wrap text-right circulating-supply" data-sort="17210662.0">
            <span data-supply="17210662.0">
            <span data-supply-container="">
            17,210,662
            </span>
            <span class="hidden-xs">
            BTC
            </span>
            </span>
        </td>"""
import re
soup = BeautifulSoup(html,'html.parser')
coin_value =  [re.findall('(\d+)', node.text.replace(',','')) for node in soup.find_all(class_="no-wrap text-right circulating-supply")]
print coin_value

打印
[[u'17210662']]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接