简体   繁体   中英

Getting API's using Python

I've been trying to grab a price from BTC-E price API,I can't just specify price[109:116] for example. because it will just print 2 numbers in the wrong format if such happened. I just need to grab whats after "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()

The price variable you retrieved from the API is

{"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}}'

That's JSON , which you can parse into a dictionary with:

import json

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM