https://www.huobi.com/p/api/contents/
你好,我想从这个 api 中提取所有的标题,看看标题是否有任何变化..我如何用 python 做?
我收到这个错误:
before_set = before['data']['items']['title']
TypeError: list indices must be integers or slices, not str
这是我的代码:
import requests
import json
try:
with open('notice.json', 'r') as current_notice:
before = json.loads(current_notice.read())
except IOError:
before = requests.get('https://www.huobi.com/p/api/contents/').json()
with open('notice.json', 'w') as current_notice:
current_notice.write(json.dumps(before))
print("First run....")
after = requests.get('https://www.huobi.com/p/api/contents/').json()
before_set = before['data']['items']['title']
after_set = after['data']['items']['title']
new_set = after_set - before_set
while True:
try:
if not new_set:
print("No change... Exiting.")
if new_set:
print("There are changes")
except Exception as e:
print(e)
pass
最佳答案
before['data']['items']
中包含的数据是一个列表。您将使用以下方式访问第一个项目的标题:
before['data']['items'][0]['title']
要获取所有标题,您可以使用列表理解:
before_set = [item['title'] for item in before['data']['items']]
关于python - 从json中提取某些数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50036071/