Python请求参数/处理api分页

cro*_*255 17 python api pagination http python-requests

我正在玩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
Run Code Online (Sandbox Code Playgroud)

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

例如. r_sanfran['page'] = 2

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

一如既往地谢谢.

天使列表API文档,如果它有用.

ale*_*cxe 20

阅读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
Run Code Online (Sandbox Code Playgroud)

  • 我猜这应该是`range(2,num_pages + 1)`因为第一页是1,而16是总页数,所以希望包含在范围内...(并且可能想要使用`requests.get('http:// ... blah ...?',params = {'page':page})`以避免字符串插值 (2认同)

dh7*_*762 12

@alecxe答案的改进:如果您使用Python Generator和请求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

for page in get_jobs():
    # TODO: process the page
Run Code Online (Sandbox Code Playgroud)

  • 这是杰出的。我能够使用它稍作修改来使用 LimitOffsetPagination 导航 drf api (5认同)