You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解析requests.get返回结果,提取CoinMarketCap所需加密货币数据

从CoinMarketCap新币页面提取格式化数据

问题说明

需要从CoinMarketCap新币页面提取结构化数据,并输出为规整的表格格式,原代码仅打印原始HTML,无法满足需求。

解决方案代码

from bs4 import BeautifulSoup
import requests

# 请求目标页面并检查请求状态
page = requests.get("https://coinmarketcap.com/new/")
page.raise_for_status()
soup = BeautifulSoup(page.text, "html.parser")

# 定位新币表格的所有行
rows = soup.select("table tbody tr")

# 打印表头
print(f"{'名称':<10} {'代号':<8} {'价格':<18} {'1小时':<8} {'24小时':<10} {'市值':<12} {'交易量':<15} {'区块链':<10}")

# 遍历每一行提取数据并格式化输出
for row in rows:
    # 提取名称和代号
    name_area = row.select_one(".name-area")
    name = name_area.select_one("p:first-of-type").text.strip() if name_area else "--"
    symbol = name_area.select_one(".coin-item-symbol").text.strip() if name_area else "--"
    
    # 提取价格
    price = row.select_one('td:nth-child(4) span').text.strip() if row.select_one('td:nth-child(4) span') else "--"
    
    # 提取1小时涨跌幅(过滤箭头符号)
    hour_change = row.select_one('td:nth-child(5) span').text.strip().replace("↓", "").replace("↑", "") if row.select_one('td:nth-child(5) span') else "--"
    
    # 提取24小时涨跌幅(过滤箭头符号)
    day_change = row.select_one('td:nth-child(6) span').text.strip().replace("↓", "").replace("↑", "") if row.select_one('td:nth-child(6) span') else "--"
    
    # 提取市值
    market_cap = row.select_one('td:nth-child(7) div').text.strip() if row.select_one('td:nth-child(7) div') else "--"
    
    # 提取交易量
    volume = row.select_one('td:nth-child(8)').text.strip() if row.select_one('td:nth-child(8)') else "--"
    
    # 提取区块链
    blockchain = row.select_one('td:nth-child(9) div').text.strip() if row.select_one('td:nth-child(9) div') else "--"
    
    # 格式化打印单条数据
    print(f"{name:<10} {symbol:<8} {price:<18} {hour_change:<8} {day_change:<10} {market_cap:<12} {volume:<15} {blockchain:<10}")

代码要点

  • 加入请求状态检查,避免处理无效响应
  • 通过CSS选择器精准定位页面元素,适配目标页面结构
  • 对每个字段做异常兼容,防止页面元素缺失导致程序崩溃
  • 使用格式化字符串实现列对齐,匹配目标表格样式

示例输出

名称        代号      价格               1小时     24小时      市值          交易量           区块链    
Cheems     Cheems   $0.00000005918    19.90%   58.53%      --           $3,774,982      zkSync    
CLIPS      Clips    $0.00005811       10.38%   9.44%       $12,697,441  $45,436,152     Ethereum  
Pooh Inu   POOH     $0.00000007305    17.69%   87.04%      $1,497,586   $332,306        BNB       

内容的提问来源于stack exchange,提问作者Drew Duazeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 23:03:29