如何使用Python获取MySQL的最新比特币价格?

时间:2018-01-26 18:41:40

标签: python

我正在尝试获取最新的比特币价格并将其保存在我的数据库中。当我执行我的python脚本时,我不断收到错误string line; string OutputFilepath = System.IO.Path.GetDirectoryName(txtSourceFile.Text); string NewFileName = OutputFilepath + string.Format(@"\Results{0}.txt", DateTime.Now.Ticks); using (System.IO.StreamWriter OutputFile = new System.IO.StreamWriter(NewFileName, true)) using (System.IO.StreamReader file = new System.IO.StreamReader(txtSourceFile.Text)) { XElement Stream; while ((line = file.ReadLine()) != null) { //Remove carriage return line feeds. line = line.Replace("
", ""); line = line.Replace("
", ""); //Create pipe delimited file. Stream = XElement.Parse(line); string PipeDelimited = (from el in Stream.Element("QUERY").Elements("ITEM") select String.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}|{14}|{15}|{16}|{17}|{18}", Text = "", Text = "", Text = "", Text = "", (string)el.Attribute("unparsedname"), Text = "", (string)el.Attribute("addr1"), Text = "", (string)el.Attribute("city"), (string)el.Attribute("state"), (string)el.Attribute("postalcode"), new RegionInfo((string)el.Attribute("countrycodeISO2")).ThreeLetterISORegionName, Text = "", Text = "01/01/" + (string)el.Attribute("dobyear"), Text = "", Text = "", Text = "", Text = "", Text = "A" ) ).Single(); { OutputFile.WriteLine(PipeDelimited); } } file.Close(); }

getdata.py

NameError: name 'price_usd' is not defined

从API返回JSON

import requests
import urllib
import json
import pymysql

con = pymysql.connect(host = 'localhost',user = 'dbuser',passwd = 'dbpass',db = 'bitcoinprice')
cursor = con.cursor()
url = 'example.com'
urllib.urlopen(url).read()
response = urllib.urlopen(url).read()
print(response)
json_obj = str(response)

cursor.execute("INSERT INTO bitcoinprice (list_price_usd) VALUES (%s)", (price_usd))
con.commit()
con.close()

print (json_obj)

模式

[
    {
        "id": "bitcoin", 
        "name": "Bitcoin", 
        "symbol": "BTC", 
        "rank": "1", 
        "price_usd": "11117.3", 
        "price_btc": "1.0", 
        "24h_volume_usd": "9729550000.0", 
        "market_cap_usd": "187080534738", 
        "available_supply": "16827875.0", 
        "total_supply": "16827875.0", 
        "max_supply": "21000000.0", 
        "percent_change_1h": "0.09", 
        "percent_change_24h": "-0.9", 
        "percent_change_7d": "-4.32", 
        "last_updated": "1516991668"
    }
]

1 个答案:

答案 0 :(得分:2)

假设你的"从api"返回json是对的:

替换

cursor.execute("INSERT INTO bitcoinprice (list_price_usd) VALUES (%s)", (price_usd))

使用

cursor.execute("INSERT INTO bitcoinprice (list_price_usd) VALUES (%s)",
    (json.loads(json_obj)[0]['price_usd']))

无论出于何种原因,您似乎已经导入了json模块(问题的解决方案)而没有实际使用它。

json.loads将json字符串转换为python对象,在您的情况下是一个包​​含一个值的列表,一个包含所需数据的字典。 [0]从列表中获取字典,['price_usd']获取您希望存储在dict中名为price_usd的变量中的值。