还有另一个线程尝试回答此问题,但是我尝试使用DictWriter保存到CSV时出现了“ str”问题。
目标:保存为CSV。
Python3: Grabbing data from Websocket and putting it into a DataFrame
from binance.client import Client
from binance.websockets import BinanceSocketManager
from binance.enums import *
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
from pandas.io.json import json_normalize
import csv
client = Client('api-key', 'api-secret')
tickers = client.get_all_tickers()
columns = ['e', 'E', 's'] # add whatever JSON keys you want
with open('names.csv', 'w', newline='') as csvfile:
fieldnames =['e', 'E', 's']
out = csv.DictWriter(open('klines.csv', 'wb'), columns,extrasaction='ignore')
out.writeheader()
### Multiplex socket
def process_message(msg):
out = csv.DictWriter(open('klines.csv', 'wb'), columns, extrasaction='ignore')
out.writeheader()
out.writerow(msg)
def printout(msg):
print(msg)
def initiate():
global bm
# Connect to client
client = Client('api-key', 'api-secret')
# Setup Socket
bm = BinanceSocketManager(client)
# then start the socket manager
conn_key = bm.start_multiplex_socket(['bnbbtc@kline_1m'], process_message)
# start the socket
bm.start()
initiate()
{'stream': 'bnbbtc@kline_1m',
'data': {'e': 'kline', 'E': 1542845036887, 's': 'BNBBTC',
'k': {'t': 1542844980000, 'T': 1542845039999, 's': 'BNBBTC', 'i': '1m', 'f': 31389820, 'L': 31389856, 'o': '0.00134810', 'c': '0.00134610', 'h': '0.00134900', 'l': '0.00134570', 'v': '1634.83000000', 'n': 37, 'x': False, 'q': '2.20069651', 'V': '613.22000000', 'Q': '0.82521938', 'B': '0'
}}}
File "C:/.../wss_multiplex.py", line 19, in <module>
out.writeheader()
File "C:\Python37_1-64\lib\csv.py", line 144, in writeheader
self.writerow(header)
File "C:\Python37_1-64\lib\csv.py", line 155, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
TypeError: a bytes-like object is required, not 'str'