【问题标题】:How do I crawl an API with multiple pages如何抓取具有多个页面的 API
【发布时间】:2017-08-08 18:24:20
【问题描述】:

我有一个带有一些 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 做点什么?

【问题讨论】:

    标签: python json api generator


    【解决方案1】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多