首页 > 解决方案 > 为什么我在使用 get 请求读取数据时得到 KeyError?

问题描述

我正在尝试使用这个简单的代码从网站读取数据,但它给了我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这里看到 response() 的全部内容: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:“浮动”对象没有属性“替换”

标签: pythonjsonweb-scrapinghttprequestget-request

解决方案


我认为您正在尝试循环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))

推荐阅读