代码之家  ›  专栏  ›  技术社区  ›  Jim Carlson

如何使用grequest从多个URL打印相同的dictionary对象?

  •  1
  • Jim Carlson  · 技术社区  · 9 年前

    我有一个URL列表,所有URL都使用相同的json结构。我试图使用grequest从所有URL中同时提取特定的字典对象。虽然我使用的是request,但我可以用一个URL来完成:

    import requests
    import json
    
    main_api = 'https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-1ST&type=both&depth=50'
    
    json_data = requests.get(main_api).json()    
    
    Quantity = json_data['result']['buy'][0]['Quantity']
    Rate = json_data['result']['buy'][0]['Rate']
    Quantity_2 = json_data['result']['sell'][0]['Quantity']
    Rate_2 = json_data['result']['sell'][0]['Rate']
    
    print ("Buy")
    print(Rate)
    print(Quantity)
    print ("")
    print ("Sell")
    print(Rate_2)
    print(Quantity_2)
    

    我想能够打印我上面打印的内容,每个URL。但我不知道从哪里开始。这是我到目前为止得到的:

    import grequests
    import json
    
    
    urls = [
        'https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-1ST&type=both&depth=50',
        'https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-2GIVE&type=both&depth=50',
        'https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-ABY&type=both&depth=50',
    ]
    
    
    requests = (grequests.get(u) for u in urls)
    responses = grequests.map(requests)
    

    我以为会是这样 print(response.json(['result']['buy'][0]['Quantity'] for response in responses)) 但这根本不起作用,python返回以下内容: print(responses.json(['result']['buy'][0]['Quantity'] for response in responses)) AttributeError: 'list' object has no attribute 'json' 。我对python和一般的编码都很陌生,如果有任何帮助,我将不胜感激。

    1 回复  |  直到 9 年前
        1
  •  1
  •   Christoph Böhme    9 年前

    你的 responses Response 物体。如果你只是用

    print(responses)
    

    它给你

    [<Response [200]>, <Response [200]>, <Response [200]>]
    

    支架 [] 回答 物体。

    responses.json(...) json() 方法。然而,列表并没有提供这样的方法,只有对象 名单上有它。

    您需要做的是访问列表中的一个元素并调用 json()

    print(responses[0].json()['result']['buy'][0]['Quantity'])
    

    这将访问 响应 列表

    for response in responses:
        print("Buy")
        print(response.json()['result']['buy'][0]['Quantity'])
        print(response.json()['result']['buy'][0]['Rate'])
        print("Sell")
        print(response.json()['result']['sell'][0]['Quantity'])
        print(response.json()['result']['sell'][0]['Rate'])
        print("----")
    

    response 变量