我尝试用这个简单的代码从网站读取数据,但它给了我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'
一些建议:
把这个移到循环之前
在那条线之前
然后进行循环并再次检查访问的级别是否正确,如下所示:
正在生成对象而不是简单的数据类型。你知道吗
一定要在代码中正确地缩进它,因为它应该在外循环中
您正在
r.items()
中循环并从每个循环中检索“p”。项目“current”没有条目“p”。你知道吗我想你是在试图循环
r["current"]
:相关问题 更多 >
编程相关推荐