问题描述
我目前正在努力创建一个从 https://coinmarketcap.com 上的表中抓取数据的程序。我看到我有点过头了。但是,我正在尝试了解这一切是如何工作的,以便能够自己完成。到目前为止,我的程序打印了加密货币等级、名称和股票代码。现在,我正在努力从表格中抓取动态变化的价格。这是我的代码:
import requests
from bs4 import BeautifulSoup
url = "https://coinmarketcap.com"
soup = BeautifulSoup(requests.get(url).content,"html.parser")
rank = 1
for td in soup.select("td:nth-of-type(3)"):
t = " ".join(tag.text for tag in td.select("p,span")).strip()
print(rank,"|",end =" "); print("{:<30} {:<10}".format(*t.rsplit(maxsplit=1)))
rank = rank + 1
for td in soup.select("td:nth-of-type(4)"):
t = " ".join(tag.text for tag in td.select("a")).strip()
print("{}_1d".format(t.rsplit(maxsplit=1)))
打印如下:
1 | Bitcoin BTC
[]_1d
2 | Ethereum ETH
[]_1d
3 | Tether USDT
[]_1d
4 | Binance Coin BNB
[]_1d
and so on...
我怎样才能让它打印加密货币的当前价格而不仅仅是文字?我可以自己弄清楚格式,只需要帮助显示实际数据。任何帮助是极大的赞赏。如果你能解释你的解决方案,那会更有帮助。
解决方法
我在您的代码中发现以下问题:
- 您的行
print("{}_1d".format(t.rsplit(maxsplit=1)))
位于内部 for 循环之外,这只会打印t
的最后一个值(为空)。 因此,需要对此进行更正以将其放入循环中,同时更改为不打印每个t
值。 - 您已将价格循环 (td:nth-of-type(4)) 置于 td:nth-of-type(3) 循环内。这使得每次外循环运行一次时,整个价格循环都会重复运行
- 如果您在循环中使用 (td:nth-of-type(4)) 打印 td 的值,您会发现在前 ~10 个结果后,您的响应中不存在标记。使用 td.text 可以获得所需的结果。
我稍微修改了您的代码以解决一些问题:
import requests
from bs4 import BeautifulSoup
url = "https://coinmarketcap.com"
soup = BeautifulSoup(requests.get(url).content,"html.parser")
rank = 1
t1,t2 = [],[]
for td in soup.select("td:nth-of-type(3)"):
t1.append(" ".join(tag.text for tag in td.select("p,span")).strip())
for td in soup.select("td:nth-of-type(4)"):
t2.append(td.text)
for i in range(0,len(t1)):
rank = rank + 1
print(rank,"|",end =" "); print("{:<30} {:<10}".format(*t1[i].rsplit(maxsplit=1)))
print("{}_1d".format(t2[i]))
,
要获取加密货币的价格,您可以使用下一个示例:
import requests
from bs4 import BeautifulSoup
url = "https://coinmarketcap.com"
soup = BeautifulSoup(requests.get(url).content,"html.parser")
for rank,td in enumerate(soup.select("td:nth-of-type(3)"),1):
t = " ".join(tag.text for tag in td.select("p,span")).strip()
price = td.find_next("td").text
print(
"{:<3} | {:<30} {:<10} {:<10}".format(
rank,*t.rsplit(maxsplit=1),price
)
)
打印:
1 | Bitcoin BTC $39,971.37
2 | Ethereum ETH $2,320.27
3 | Tether USDT $1.00
4 | Binance Coin BNB $314.10
5 | Cardano ADA $1.28
6 | XRP XRP $0.7078
7 | USD Coin USDC $1.00
8 | Dogecoin DOGE $0.2043
9 | Polkadot DOT $15.11
10 | Binance USD BUSD $1.00
11 | Uniswap UNI $19.24
12 | Bitcoin Cash BCH $517.07
13 | Litecoin LTC $140.07
14 | Chainlink LINK $19.02
15 | Solana SOL $29.55
16 | Wrapped Bitcoin WBTC $39923.81
17 | Polygon MATIC $1.02
18 | Stellar XLM $0.27
19 | Ethereum Classic ETC $48.75
20 | THETA THETA $5.99
...and so on.