gpt4 book ai didi

python - 如何爬取具有多个页面的 API

转载 作者:太空宇宙 更新时间:2023-11-04 05:01:40 24 4
gpt4 key购买 nike

我有一个带有一些 JSON 的 API 的 url:

{
"posts": [ ... ],
"page": { ... },
"next": "/posts.json?page=2"
}

其中 /posts.json?page=2 具有不同的页码,如果没有更多页,则可能为 null

如何在 Python 中创建一个函数来输出包含所有帖子的所有页面?

我想我将不得不做类似的事情

def get_posts(url, posts=[]):
json = request(url).json()

posts.append(json.posts)

while json.next_page:
return get_posts(json.next_page, posts)

但我想我可以用 yield 做点什么?

最佳答案

def get_posts(url, posts=None):
# initialize the posts lists
posts = [] if posts is None else posts

# make the request and convert to json
json = request(url).json()

# extends the posts array with the returned posts
posts.extend(json['posts'])

# if there is a next_page, call the function recursively
if json.next_page:
return get_posts(json.next_page, posts)

# if there isn't a next_page, return the posts
return posts

关于python - 如何爬取具有多个页面的 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com