用于 API json 集合的嵌套 while 循环



我正在从Meetup API请求590个页面。我已经迭代了一个while循环来获取页面。现在我有了请求此页面所需的页面,并将它们正确格式化为 python,以便放入 Pandas 数据帧中。

当您为一个url 执行此操作时,它的外观是这样的:

url = ('https://api.meetup.com/2/groups?offset=1&format=json&category_id=34&photo-host=public&page=100&radius=200.0&fields=&order=id&desc=false&sig_id=243750775&sig=768bcf78d9c73937fcf2f5d41fe6070424f8d0e3')
r = requests.get(url).json()
data = pd.io.json.json_normalize(r['results'])

但是因为我有这么多页面,所以我想自动执行此操作并遍历所有页面。

这就是嵌套循环的方式,这就是我尝试过的:

urls = 0
offset = 0
url = 'https://api.meetup.com/2/groups?offset=%d&format=json&category_id=34&photo-host=public&page=100&radius=200.0&fields=&order=id&desc=false&sig_id=243750775&sig=768bcf78d9c73937fcf2f5d41fe6070424f8d0e3'
r = requests.get(urls%d = 'https://api.meetup.com/2/groups?offset=%d&format=json&category_id=34&photo-host=public&page=100&radius=200.0&fields=&order=id&desc=false&sig_id=243750775&sig=768bcf78d9c73937fcf2f5d41fe6070424f8d0e3').json()
while urlx < 591:
new_url = r % urls % offset
print(new_url)
offset += 1  

但是,它不起作用,我收到许多错误,包括这个错误:

语法错误:关键字不能是表达式

不确定您要做什么,并且代码有很多问题。

但是,如果您只想遍历 0 到 591 并获取 URL,那么这里是代码:

import requests
import pandas as pd
dfs = []
base_url = 'https://api.meetup.com/2/groups?offset=%d&format=json&category_id=34&photo-host=public&page=100&radius=200.0&fields=&order=id&desc=false&sig_id=243750775&sig=768bcf78d9c73937fcf2f5d41fe6070424f8d0e3'
for i in range(0, 592):
url = base_url % i
r = requests.get(url).json()
print("Fetching URL: %sn" % url)
# do something with r here
# here I'll append it to a list of dfs
dfs.append(pd.io.json.json_normalize(r['results']))

最新更新