如何通过API进行Reddit全站搜索而非子版块搜索?
实现Reddit全站搜索API方案
完全可以通过API实现和Reddit GUI搜索一致的全站搜索功能,不管是使用官方API还是你提到的PRAW库都能做到,以下是具体实现方法:
使用PRAW实现全站搜索
PRAW的reddit.search()方法默认就是全站范围的搜索,无需指定子版块,同时支持筛选不同类型的内容:
1. 初始化PRAW
首先确保已配置好Reddit开发者应用的凭证:
import praw # 初始化Reddit客户端 reddit = praw.Reddit( client_id="你的客户端ID", client_secret="你的客户端密钥", user_agent="自定义用户代理格式:[应用名]/[版本] by u/[你的Reddit用户名]" )
2. 全站搜索帖子(Posts)
默认搜索结果就是帖子,可指定排序方式和数量:
# 搜索关键词"python",按热度排序,返回前10条结果 for submission in reddit.search("python", sort="hot", limit=10): print(f"标题:{submission.title} | 子版块:r/{submission.subreddit} | 点赞数:{submission.score}")
3. 全站搜索评论(Comments)
通过params参数指定搜索类型为comment即可:
# 搜索包含"python"的全站评论,返回前10条 for comment in reddit.search("python", params={"type": "comment"}, limit=10): print(f"评论内容:{comment.body[:100]}... | 所属帖子:{comment.submission.title}")
4. 搜索相关子版块(Subreddits)
使用reddit.subreddits.search()方法直接搜索全站相关子版块:
# 搜索和"python"主题相关的子版块,返回前10条 for subreddit in reddit.subreddits.search("python", limit=10): print(f"子版块:r/{subreddit.display_name} | 描述:{subreddit.public_description[:100]}...")
直接调用Reddit官方API
如果不想用PRAW,也可以直接通过HTTP请求调用官方API,需要先完成OAuth认证:
- 搜索帖子:
GET https://oauth.reddit.com/search?q=你的关键词&type=link - 搜索评论:
GET https://oauth.reddit.com/search?q=你的关键词&type=comment - 搜索子版块:
GET https://oauth.reddit.com/subreddits/search?q=你的关键词
请求时需在Header中携带Authorization: Bearer [你的访问令牌]和User-Agent信息。
内容的提问来源于stack exchange,提问作者FahdS
相关产品推荐
相关产品推荐

