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

比特币价格爬取代码失效,寻求技术协助

修复比特币价格数据采集代码的方案

原代码失效是因为目标网站的页面结构和数据格式发生了变更,以下是适配后的修复方案:

修复后的完整代码

# -*- coding: UTF-8 -*-  
import requests
import datetime
from bs4 import BeautifulSoup
import json
import re

first_date = datetime.datetime(2010, 7, 16)

url_price = 'https://bitinfocharts.com/comparison/bitcoin-price.html#alltime'

# 获取页面内容
response_price = requests.get(url_price)
soup_price = BeautifulSoup(response_price.text, 'lxml')

# 定位存储价格数据的script标签(通过关键词匹配,避免固定索引失效)
target_script = None
for script in soup_price.find_all('script'):
    if 'datasets' in script.text and 'bitcoin-price' in script.text:
        target_script = script.text
        break

if not target_script:
    print("找不到存储价格数据的脚本标签")
    exit()

# 提取数据数组部分
data_match = re.search(r'data:\s*(\[.*?\])', target_script)
if not data_match:
    print("提取不到价格数据内容")
    exit()

price_data = json.loads(data_match.group(1))

# 处理数据,过滤指定日期并格式化
formatted_data = []
for timestamp_ms, price in price_data:
    # 将毫秒级时间戳转换为datetime对象
    date = datetime.datetime.fromtimestamp(timestamp_ms / 1000)
    if date > first_date:
        # 转换为原代码所需的日期字符串格式
        date_str = f'new Date("{date.strftime("%Y/%m/%d")}")'
        formatted_data.append(f'[{date_str}, {price}]')

# 写入文件
with open("btc-price.txt", "w", encoding="utf-8") as f:
    f.write(', '.join(formatted_data))

关键修复说明

  • 取消固定script标签索引:原代码硬取第4个script标签,现在通过datasets和bitcoin-price关键词匹配目标脚本,避免页面结构变动导致定位失败
  • 适配新数据格式:网站现在以[毫秒时间戳, 价格]的数组形式存储数据,改用JSON解析替代原有的正则匹配,稳定性更高
  • 日期逻辑优化:将时间戳转成datetime对象,过滤掉2010年7月16日之前的数据,再转成原代码需要的日期字符串样式
  • 文件操作优化:使用with语句自动管理文件资源,避免手动关闭文件可能出现的泄漏问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:23:15