【问题标题】:Get data from API and save it to txt with Python从 API 获取数据并使用 Python 将其保存到 txt
【发布时间】:2018-04-10 18:42:18
【问题描述】:

我需要从此 API https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434(示例节点)获取数据

这是我的代码(python):

导入请求 f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434') 打印 f.text

我只想在 txt 文件的后续三行中保存协议、响应时间和信誉。它应该看起来像这样::

协议:1.2.0 响应时间:8157.912472694088 声望:1377

不幸的是,我被困在这一点上,我无法以任何方式处理这些数据

【问题讨论】:

    标签: python api get


    【解决方案1】:
    import requests
    f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
    
    # Store content as json
    answer = f.json()
    
    # List of element you want to keep
    items = ['protocol', 'responseTime', 'reputation']
    
    # Display
    for item in items:
        print(item + ':' + str(answer[item]))
    
    # If you want to save in a file
    with open("Output.txt", "w") as text_file:
        for item in items:
            print(item + ':' + str(answer[item]), file=text_file)
    

    希望对您有所帮助!干杯

    【讨论】:

      【解决方案2】:

      您只需转换为 JSON 对象即可访问密钥

      import requests
      import simplejson as json
      
      f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
      
      x = json.loads(f.text)
      
      print 'protocol: {}'.format(x.get('protocol'))
      print 'responseTime: {}'.format(x.get('responseTime'))
      print 'reputation: {}'.format(x.get('reputation'))
      

      【讨论】:

        【解决方案3】:

        这是一种非常不完善的方式来做你想做的事情,你可以建立起来。您需要为 text.txt 添加路径/文件名。

        import requests
        import json
        
        f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434')
        t = json.loads(f.text)
        
        with open('text.txt', 'a') as mfile:
          mfile.write("protocol: {0}".format(str(t['protocol'])))
          mfile.write("responseTime: {0}".format(str(t['responseTime'])))
          mfile.write("reputation: {0}".format(str(t['reputation'])))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-05
          • 1970-01-01
          • 2021-10-21
          • 2021-01-31
          • 2022-01-15
          • 1970-01-01
          相关资源
          最近更新 更多