python - 为什么我在使用 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:“浮动”对象没有属性“替换”
解决方案
我认为您正在尝试循环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))
推荐阅读
- flutter - 将参数传递给另一个组件 - null
- php - laravel 7.14 在使用关系搜索数据表后为产品构建链接
- r - 向热图添加图例
- html - 如何使我的网页中的屏幕阅读器可以访问图像?当图像可访问时是什么意思?
- deep-learning - Tensorboard 2.2.1 Windows 10-当前数据集没有激活的仪表板
- cassandra-3.0 - 删除 Cassandra 容器时如何保留数据和架构
- c++ - UTF-8:输入文本和硬编码之间的不同行为
- google-chrome - 在 HTML 页面中从 URL 中选择并以黄色突出显示的文本
- java - 我对编程很陌生,想知道如何在我的 GUI 上显示 JButton
- java - ByteBuddy 是否可以使用 ASM 来实现一个方法