为什么在使用get请求读取数据时会出现KeyError?

2024-09-26 22:49:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用这个简单的代码从网站读取数据,但它给了我KeyError['p']

for i in range(25200):

    time.sleep(1)
    with requests.Session() as s:
               data = {'current' : 'afghan_usd' }
               r = s.get('http://call5.tgju.org/ajax.json?2019061716-20190617171520-I4OJ3OcWf4gtpzr3JNC5', json = data ).json()
               #print(r)
    for key, value in r["current"].items():
        last_prices = (r[key]['p'])
        z.append(last_prices)
        mid.append(mean(z)) 

给定的r是这样的:

{'current': {'afghan_usd': {'p': '154530', 'h': '157260', 'l':
 '154530', 'd': '3640', 'dp': 2.36, 'dt': 'low', 't': '۱۷:۲۷:۰۳',
 't_en': '17:27:03', 't-g': '۱۷:۲۷:۰۳', 'ts': '2019-06-17 17:27:03'}}

您可以在这里看到响应(r)的完整内容:https://github.com/rezaee/coursera-test/issues/1

编辑:

我这样编辑代码:

for i in range(25200):

    time.sleep(1)
    with requests.Session() as s:
               data = {'current' : 'afghan_usd' }#code}
               r = s.get('http://call5.tgju.org/ajax.json?2019061716-20190617171520-I4OJ3OcWf4gtpzr3JNC5', json = data ).json()
               #print(r)

    for key, value in r["current"]["afghan_usd"].items():
        last_prices = float(value.replace("," , ""))
        z.append(last_prices)
        mid.append(mean(z)) 

但我有一个新的错误:

AttributeError: 'float' object has no attribute 'replace'


Tags: key代码injsonfordatatimevalue
3条回答

一些建议:

把这个移到循环之前

with requests.Session() as s:

在那条线之前

data = {'current' : 'afghan_usd' }

然后进行循环并再次检查访问的级别是否正确,如下所示:

last_prices = (r[key]['p'])

正在生成对象而不是简单的数据类型。你知道吗

一定要在代码中正确地缩进它,因为它应该在外循环中

for key, value in r.items():

您正在r.items()中循环并从每个循环中检索“p”。项目“current”没有条目“p”。你知道吗

我想你是在试图循环r["current"]

for key, value in r["current"].items():
    # for first iteration:
    # key is afghan_usd
    # value is {'p': ....}
    try:
        price = value["p"]
    except TypeError:  # value is a string
        price = value
    last_prices = float(price.replace(',', ''))
    z.append(last_prices)
    mid.append(mean(z))

相关问题 更多 >

    热门问题