Python请求参数/处理api分页

问题描述 投票:15回答:2

我正在玩Angel List(AL)API,想要在圣旧金山开展所有工作。因为我找不到api的活动Python包装器(如果我取得任何进展,我想我想自己制作),我正在使用请求库。

AL API的结果是分页的,我无法弄清楚如何超越结果的第一页。

这是我的代码:

import requests
r_sanfran = requests.get("https://api.angel.co/1/tags/1664/jobs").json()
r_sanfran.keys()
# returns [u'per_page', u'last_page', u'total', u'jobs', u'page']
r_sanfran['last_page']
#returns 16
r_sanfran['page']
# returns 1

我尝试向requests.get添加参数,但这不起作用。我也尝试过一些非常愚蠢的东西 - 改变“页面”键的价值,就像那神奇地为我分页。

例如。 r_sanfran['page'] = 2

我猜它是相对简单的东西,但我似乎无法弄明白所以任何帮助都会很棒。

一如既往地谢谢。

Angel List API documentation若有帮助。

python api http pagination python-requests
2个回答
18
投票

阅读last_page并为该范围内的每个页面发出get请求:

import requests

r_sanfran = requests.get("https://api.angel.co/1/tags/1664/jobs").json()
num_pages = r_sanfran['last_page']

for page in range(2, num_pages + 1):
    r_sanfran = requests.get("https://api.angel.co/1/tags/1664/jobs", params={'page': page}).json()
    print r_sanfran['page']
    # TODO: extract the data

8
投票

改进@ alecxe的答案:如果您使用Python生成器并请求HTTP会话,则可以在查询大量页面或非常大的页面时提高性能和资源使用率。

import requests

session = requests.Session()

def get_jobs():
    url = "https://api.angel.co/1/tags/1664/jobs" 
    first_page = session.get(url).json()
    yield first_page
    num_pages = first_page['last_page']

    for page in range(2, num_pages + 1):
        next_page = session.get(url, params={'page': page}).json()
        yield next_page['page']

for page in get_jobs():
    # TODO: process the page
© www.soinside.com 2019 - 2024. All rights reserved.