【问题标题】:Why do I get KeyError while reading data with get request?为什么我在使用 get 请求读取数据时得到 KeyError?
【发布时间】:2019-10-31 02:36:07
【问题描述】:

我正在尝试这个简单的代码从网站读取数据,但它给了我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' 对象没有属性 'replace'

【问题讨论】:

  • 这里缺少一些东西:'current': , 'afghan_usd',逗号和冒号之间。你确定你的输出吗?
  • @olinox14:对不起,我修好了。实际输出有许多其他对象,我只想复制特定的对象。

标签: python json web-scraping httprequest get-request


【解决方案1】:

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

【讨论】:

  • 感谢您的帮助。我正在尝试运行您的代码。对于您的问题,因为我正在尝试在线绘制我的图表。所以我在循环中使用mean()
  • 您的代码出现此错误:TypeError: can't convert type 'str' to numerator/denominator
  • 你还没有发布完整的回复,但是如果p的值总是一个整数,你可以写last_prices = int(value['p'])
  • ValueError: int() 基数为 10 的无效文字:'126,693'
  • 这是一个很好的答案。而ValueError 来自您试图获取字符串的mean 的事实。考虑将last_prices = (value['p']) 更改为last_prices = float(value['p'])
【解决方案2】:

一些建议:

在循环之前移动它

with requests.Session() as s:

在那一行之前有

data = {'current' : 'afghan_usd' }

然后让您的循环并仔细检查您访问的级别是否正确,如下所示:

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

正在生成一个对象而不是简单的数据类型。

确保在代码中正确缩进,因为它应该在外部循环中

for key, value in r.items():

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 我应该如何解决它?我很困惑。
    • 你可以试试last_prices = r['key'].get('p'),然后检查last_prices是否有值,如if last_prices: z.append(last_prices)
    • 再次`KeyError: 'key' `
    • 错了:他正在迭代r["current"].items(),而不是r.items()
    • @olinox14 OP 已经多次编辑了这个问题。原来是 r.items()
    猜你喜欢
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 2018-06-09
    • 2021-09-02
    • 2015-07-10
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多