【网络爬虫 | Python】数字货币ok链上bitcoin大额交易实时爬取,存入 mysql 数据库
import requests
import pymysql
import time
# 连接MySQL数据库
def connect_db():
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
database='your_database',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
return connection
# 将数据插入MySQL数据库
def insert_db(data, connection):
try:
with connection.cursor() as cursor:
sql = "INSERT INTO btc_trade (trade_id, amount, price, time) VALUES (%s, %s, %s, %s)"
cursor.execute(sql, data)
connection.commit()
except pymysql.MySQLError as e:
print(e)
# 获取ok链上bitcoin大额交易数据
def get_btc_trade(url):
response = requests.get(url)
return response.json()
# 主程序
def main():
url = 'https://www.okcoin.com/api/v1/btc_cny/trades?since=0'
connection = connect_db()
while True:
trades = get_btc_trade(url)
for trade in trades:
data = (trade['tid, trade['amount'], trade['price'], trade['time']))
insert_db(data, connection)
time.sleep(10) # 间隔10秒
if __name__ == "__main__":
main()
在这个代码实例中,我们首先定义了连接MySQL数据库的函数connect_db
,然后定义了将数据插入数据库的函数insert_db
。get_btc_trade
函数负责从OKEx获取交易数据。最后,在main
函数中,我们连接数据库,进入一个无限循环,每10秒获取一次数据并插入数据库。这个例子展示了如何将数据实时地从一个API抓取并存储到数据库中。
评论已关闭