我想将WordPress API的JSON响应与Python的库请求连接在一起。这是我的代码:
import requests
results = []
pagination = 1
url = 'https://example.com/wp-json/wp/v2/posts?after=2019-01-01T00:00:00&before=2019-02-01T00:00:00&per_page=5&page={}'.format(pagination)
r = requests.get(url)
data = r.json()
for i in data:
results.append(i)
while r.status_code == 200:
pagination += 1
r = requests.get(url)
data = r.json()
for i in data:
results.append(i)
else:
break
print(results)
我只停留在第一页。
答案 0 :(得分:1)
您在初始设置URL格式时绑定了该值,此值将不再更新。
传递某些params as a dictionary to requests而不是传递URL可能更容易,并且每次迭代都进行分页更新,例如:
import requests
results = []
pagination = 1
url = 'https://example.com/wp-json/wp/v2/posts?after=2019-01-01T00:00:00&before=2019-02-01T00:00:00'
params = {'per_page': 5, 'page': pagination}
r = requests.get(url, params=params)
data = r.json()
for i in data:
results.append(i)
while r.status_code == 200:
pagination += 1
params.update({'page': pagination})
r = requests.get(url, params=params)
data = r.json()
for i in data:
results.append(i)
else:
break
print(results)