Skip to main content
 首页 » 编程设计

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

2025年02月15日8jiqing9006

我有一个带有一些 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