从python中的惊奇API获取数据时出现关键错误

时间:2019-03-19 20:31:31

标签: python python-3.x

我正在尝试从惊奇API获取数据并将其保存在CSV文件中。我成功获取并读取了数据,但是最后,由于找不到数据,但是数据正在写入CSV文件中,我遇到了关键错误

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-6-4dbd9841fff9> in <module>
     75 
     76 #paged_requests_characters()
---> 77 paged_requests_comics()
     78 

<ipython-input-6-4dbd9841fff9> in paged_requests_comics(page_size)
     61         j = resp.json()
     62         #print(j)
---> 63         comic_json = j['data']['results']
     64         #print(comic_json)
     65         comic_csvwriter = csv.writer(open('comics.csv','a'))

KeyError: 'data'

这是我的代码

public_key = 'yourpublickey'
private_key = 'yourprivatekey'
COMIC_URL = 'http://gateway.marvel.com/v1/public/comics'
#Timestamp,hash and encodings
def get_link_params():
    ts = time.time();
    ts_str = str(int(ts));
    m_hash = hashlib.md5();
    ts_str_byte = bytes(ts_str, 'utf-8');
    private_key_byte = bytes(private_key, 'utf-8');
    public_key_byte = bytes(public_key, 'utf-8');
    m_hash.update(ts_str_byte + private_key_byte + public_key_byte);
    m_hash_str = str(m_hash.hexdigest());
    return {'ts': ts_str, 'hash': m_hash_str};

def paged_requests_comics(page_size = 100):
    params = {'apikey': 'public_key', 'limit': page_size}
    hash_params = get_link_params()
    params.update(hash_params)
    comic_resp = requests.get(COMIC_URL, params)
    j = comic_resp.json()
    total = j['data']['total']
    page_no = total/page_size
    print(page_no)
    rounded_page_no= round(page_no)
    print(rounded_page_no)
    for i in range(rounded_page_no): 
        hash_params = get_link_params()
        params.update(hash_params)
        params.update({'offset': page_size * i}) # offset, how many records to skip
        comic_resp = requests.get(COMIC_URL, params)
        j = comic_resp.json()
        #print(j)
        comic_json = j['data']['results']
        #print(comic_json)
        comic_csvwriter = csv.writer(open('comics.csv','a'))
        count=0
        for a in comic_json:
            if(count==0):
                header = a.keys()
                comic_csvwriter.writerow(header)
                count+=1
            comic_csvwriter.writerow(a.values())
    print('Done')

Marvel API文档:developer.marvel.com

我该怎么办?

0 个答案:

没有答案