简体   繁体   中英

Python(requests) How to parse only certain json data, How to make this chunk of code loop (not as important)

Figured it out thanks to Loki !

Every 1 second logs data from print(get_rates()) function to a .txt file, so I made an infinite while loop (suggested by loki)

import requests
from time import sleep
from datetime import datetime,date

old_print = print 
def tstamped_print(*args, **kwargs):
  old_print(datetime.now(), *args, **kwargs)
print = tstamped_print

# Getting rates
def get_rates():
    PREEVURL = requests.get('http://preev.com/pulse/units:btc+usd/sources:bitstamp+kraken')
    DATA = PREEVURL.json()
    RESULT = {}
    for key, value in DATA["btc"]["usd"].items():
        RESULT[key] = (value['last'])
    return RESULT

# Infinite while loop
a = 1
while a < 10:
    print(get_rates(),file=open("btc_price1.txt", "a"))
    print(get_rates())
    sleep(2)
    a = a - 0
else:
    print("loop end")

If I understand well, you want to do two things:

  1. Extract a bitcoin rate from this api response
  2. Loop requests and store each result in an file to save the history

Let's see how to do this:

  1. Call the api and store the result

If you call it in a python shell you can look at the data:

>>> import requests
>>> 
>>> url_resp = requests.get('http://preev.com/pulse/units:btc+usd/sources:bitstamp+kraken') # (your url)
>>> data = url_resp.json()
>>> data
{'btc': {'usd': {'bitstamp': {'last': '9503.05', 'volume': '6.27734e+7'}, 'kraken': {'last': '9509.10', 'volume': '4.08549e+7'}}}, 'other': {'slot': None, 'ver': 'b'}}

To get the value really simply access each dictionnary item by its key:

# Convert the string to float number.
bitsamp_rate = float(data['btc']['usd']['bitstamp']['last'])
kraken_rate = float(data['btc']['usd']['kraken']['last'])

Let's loop over each exchange and put it in a function:

def get_rates():
    url_resp = requests.get('http://preev.com/pulse/units:btc+usd/sources:bitstamp+kraken') # (your url)
    data = url_resp.json()
    result = {}
    for exchange, rates in data['btc']['usd'].items():
        result[exchange] = float(rates['last'])
    return result
  1. Use a while loop to call the function multiple times

I'm letting you decide how to store the data, you might want to record the time when the function was called also.

The problem is that your initial data.json file is empty. The easiest way out is to place an empty dictionary or something in your data.json file. Just make sure data.json is not an empty file.

Figured it out thanks to Loki !

Every 1 second logs data from each print(get_rates()) function to a .txt file, so I made an infinite while loop (suggested by loki)

import time
import requests
import datetime
from time import sleep
from datetime import datetime,date


'''
print('Enter correct username and password combo to continue')
count = 0
username = '420'
while count < 10:
    username = input('login code: ')
    if username== '420':
        print('Access granted')
        count = 11
        break
    else:
        print('Access denied. Try again.')
        count =- 1
print('====> LOGGED IN','\n')
'''     

today = time.strftime("(%Y-%m-%d %I:%M%p)")
old_print = print
def tstamped_print(*args, **kwargs):
  old_print(today, *args, **kwargs)
print = tstamped_print

# Getting rates
def get_rates():
    PREEVURL = requests.get('http://preev.com/pulse/units:btc+usd/sources:bitstamp+kraken')
    DATA = PREEVURL.json()
    RESULT = {}
    for key, value in DATA["btc"]["usd"].items():
        RESULT[key] = (value['last'])
    return RESULT

# Infinite while loop
a = 1
PREEVURL = requests.get('http://preev.com/pulse/units:btc+usd/sources:bitstamp+kraken')
DATA = PREEVURL.json()
while a < 10:
    print(get_rates(), file=open("btc_price1.txt", "a"))
    print(get_rates())
    sleep(1)
    a = a - 0
else:
    print("loop end")

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