You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Reddit API获取列表结果的下一页数据?

搞定Reddit API翻页的正确姿势

嘿,我来帮你解决这个翻页问题!你已经成功拿到了第一页的after值,这正是Reddit API翻页的核心——只要把这个值传给下一次请求,就能获取下一页的内容了。

我给你调整了代码,让它能循环获取多页内容,还补上了容易踩坑的细节:

import requests

def fetch_reddit_posts(subreddit, max_pages=3):
    base_url = f'https://www.reddit.com/r/{subreddit}/top.json?sort=top&show=all&t=all'
    next_page_token = None
    
    for _ in range(max_pages):
        # 拼接请求URL,带上翻页参数
        request_url = f"{base_url}&after={next_page_token}" if next_page_token else base_url
        # 关键:必须添加User-Agent,否则Reddit会拒绝你的请求
        headers = {"User-Agent": "My Custom Reddit Tool/1.0"}
        response = requests.get(request_url, headers=headers)
        post_list = response.json()
        
        # 遍历当前页的所有帖子
        for entry in post_list['data']['children']:
            post_data = entry['data']
            print(f"帖子得分: {post_data['score']}, 标题: {post_data['title']}")
        
        # 更新下一页的标识,准备发起下一次请求
        next_page_token = post_list['data']['after']
        # 如果没有下一页了,直接终止循环
        if not next_page_token:
            print("已经没有更多内容啦!")
            break

# 调用函数,获取Petscop板块最多3页的热门帖子
fetch_reddit_posts('Petscop', max_pages=3)

这里有几个你必须注意的点:

  • User-Agent必填:Reddit的API会拦截没有User-Agent的请求,所以一定要在请求头里加上这个字段,随便写一个能标识你工具的名称就行。
  • 终止循环的时机:当after返回None时,说明已经到最后一页了,这时候必须停止请求,不然会得到无效的响应。
  • URL参数的正确写法:你原来URL里的&是HTML转义后的符号,代码里直接用&拼接参数就可以了。

内容的提问来源于stack exchange,提问作者Nathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:11:35