Python JSON至CSV分页循环

时间:2018-07-16 20:33:27

标签: python json loops csv pagination

我正在使用API​​ URL尝试将JSON转换为CSV,这在使用&page = 1时不是问题,但是在尝试通过更多结果进行分页时却遇到了一些问题。

我不确定使用一阵子还是嵌套for循环遍历页面是否更好。

感谢您的帮助!

import requests
import getpass
import json
import unicodecsv as csv

url = 'https://xxxx.com?perPage=100&token=' + access_token + '&page=' + str(page)
page = 1
outfile = 'example.csv'
ofile = open(outfile,'w')
writer = csv.writer(ofile, dialect='excel', encoding='utf-8', delimiter='\t')
ofile.write('Name')
ofile.write(',')
ofile.write('Email')
ofile.write(',\n')
response = requests.get(url)
json_data = response.json()

for item in json_data['information']:
    ofile.write(item['person']['name'])
    ofile.write(',')
    ofile.write(item['person']['email'])
    ofile.write(',\n')

取决于URL,可能只有一页或很多页,所以我没有设置范围。我当时正在考虑尝试使用while json_data['information'] != []之类的方法,因为一旦页面计数过高,JSON只会显示{"invitations":[]}

编辑:

我可以使用while循环,但是我觉得可能有更好的方法。更新的代码:

import requests
import getpass
import json
import unicodecsv as csv

page = 1
url = 'https://xxxx.com?perPage=100&token=' + access_token + '&page=%s' % page
page = 1
outfile = 'example.csv'
ofile = open(outfile,'w')
writer = csv.writer(ofile, dialect='excel', encoding='utf-8', delimiter='\t')
ofile.write('Name')
ofile.write(',')
ofile.write('Email')
ofile.write(',\n')
response = requests.get(url)
json_data = response.json()
while json_data['information'] != []:
    for item in json_data['information']:
        ofile.write(item['person']['name'])
        ofile.write(',')
        ofile.write(item['person']['email'])
        ofile.write(',\n')
    page += 1
    url = 'https://xxxx.com?perPage=100&token=' + access_token + '&page=%s' % page
    response = requests.get(url)
    json_data = response.json()

0 个答案:

没有答案