使用Beautiful Soup 4提取特定列表项

问题描述 投票:0回答:1

我试图从this webpage中提取“Balance”整数值,但我很难搞清楚如何隔离该列表项。

这是我目前的代码:

import bs4, requests

res = requests.get('https://live.blockcypher.com/btc/address/3CpfD1gBBdNW7orErj3YyNNSVpzndZ9aP9/')
res.raise_for_status()

soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = [elem for elem in soup.findAll('li') if 'Balance' in str(elem.text)]

print(elems)

然而,当我运行它时,我得到的是[]而不是实际的平衡值。

关于我哪里出错的任何想法?

python beautifulsoup
1个回答
1
投票

要获得该号码,您可以使用此:

balance = soup.find('span', text='Balance').parent.contents[3].strip()
print(balance)

输出:

9.06451275 BTC

说明:

soup.find('span', text='Balance')会给你这个<span class="dash-label">Balance</span>标签。

使用.parent.contents会将其父标记的内容作为列表。在该列表中,您需要的文本位于第3个索引中。

>>> for i, content in enumerate(soup.find('span', text='Balance').parent.contents):
...     print(i, content)
...
0

1 <span class="dash-label">Balance</span>
2 <br/>
3
            9.06451275 BTC


4 <br/>
5

6 <span class="dash-label">
                (-0.0500349 BTC unconfirmed)
              </span>
7
© www.soinside.com 2019 - 2024. All rights reserved.