正在使用Python获取API

2024-09-30 02:15:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试从BTC-E price API获取一个价格,我不能仅仅指定price[109:116]作为例子。因为如果发生这种情况,它只会以错误的格式打印2个数字。我只需要抓住“最后一次”之后的内容

from urllib2 import Request, urlopen, URLError

def btceapi():
    request = Request('https://btc-e.com/api/2/btc_usd/ticker')
    try:
        response = urlopen(request)
        price = response.read()
        print price[109:116]
    except URLError, e:
        print 'Not Found'

btceapi()

Tags: apiresponserequest错误情况价格price例子
1条回答
网友
1楼 · 发布于 2024-09-30 02:15:31

从API检索到的price变量是

{"ticker":{"high":298.99899,"low":263.20001,"avg":281.0995,"vol":10566249.17861,"vol_cur":37737.87504,"last":291,"buy":291.493,"sell":291.001,"updated":1436554875,"server_time":1436554876}}'

这就是JSON,你可以用它解析成字典:

import json

<snip...>
    price = response.read()
    print json.loads(price)["ticker"]["last"]

相关问题 更多 >

    热门问题