2017-08-08 54 views
1

我有一个网址与一些JSON的API:如何抓取一个API多页

{ 
    "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

回答

0
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 
+3

你能为此代码添加解释吗? –