使用Python获取API

时间:2015-07-10 18:58:26

标签: python

我一直试图从BTC-E价格API中获取价格,但我不能仅指定price[109:116]。因为如果发生这种情况,它只会以错误的格式打印2个数字。我只需要在" last:"

之后抓住什么
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()

1 个答案:

答案 0 :(得分:3)

您从API检索到的price变量是

  

{ “股票”:{ “高”:298.99899, “低”:263.20001, “平均”:281.0995, “体积”:10566249.17861, “vol_cur”:37737.87504, “最后”:291, “买”:291.493 , “卖”:291.001, “已更新”:1436554875, “server_time”:1436554876}}“

那是JSON,你可以用以下内容解析成字典:

import json

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