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

时间:2018-03-01 09:10:49

标签: python beautifulsoup

我正在尝试从this webpage中提取“余额”整数值,但我无法弄清楚如何隔离该列表项。

这是我目前的代码:

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)

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

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

1 个答案:

答案 0 :(得分: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