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
我尝试添加参数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
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
| 归档时间: | 
 | 
| 查看次数: | 22942 次 | 
| 最近记录: |