我正在玩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
,但那没用。我也尝试过一些非常愚蠢的东西 - 改变'page'键的价值,就像魔法般地为我分页一样。
例如。 r_sanfran['page'] = 2
我猜它是相对简单的东西,但我似乎无法弄明白所以任何帮助都会很棒。
一如既往地谢谢。
Angel List API文档 如果它有用
读 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
读 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
改进@ 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