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

使用PRAW调用Reddit API获内容,CSV生成后为空的问题排查

问题排查与修复方案

核心问题1:subreddit.search(query=None) 无法返回有效结果

PRAW的search方法需要传入有效查询关键词,传入query=None不符合API调用规则,不会返回任何帖子。如果要获取子版块最近一周的帖子,直接使用子版块的new方法(对应“按最新排序”)即可,无需用search接口。

核心问题2:时区不统一导致时间过滤失效

你的start_time是本地时间,但submission.created_utc是UTC时间,转成datetime后仍为UTC时区,两者直接比较会因时区差过滤掉所有符合条件的内容,必须统一为UTC时区进行比较。

额外问题:未处理作者已删除的情况

部分帖子或评论的作者账号可能已被删除,直接调用.name会抛出AttributeError,可能中断数据写入流程,需要增加判断规避。


修复后的完整代码

import praw
import pandas as pd
import datetime as dt
import csv

reddit = praw.Reddit(client_id='my client ID',
                     client_secret='my secret',
                     user_agent='my agent')

subreddit = reddit.subreddit("booksuggestions")

# 统一使用UTC时区计算时间范围
end_time_utc = dt.datetime.utcnow()
start_time_utc = end_time_utc - dt.timedelta(days=7)

with open("booksuggestions_data.csv", mode="w", newline="", encoding="utf-8") as csv_file:
    fieldnames = ["type", "id", "created_utc", "author", "body"]
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()

    # 直接获取最近一周的最新帖子,替代search方法
    for submission in subreddit.new(time_filter="week"):
        try:
            submission_time = dt.datetime.utcfromtimestamp(submission.created_utc)
            if submission_time >= start_time_utc:
                # 处理作者为空的情况
                author_name = submission.author.name if submission.author else "[deleted]"
                writer.writerow({
                    "type": "post",
                    "id": submission.id,
                    "created_utc": submission.created_utc,
                    "author": author_name,
                    "body": submission.selftext,
                })

            # 加载所有评论
            submission.comments.replace_more(limit=None)
            for comment in submission.comments.list():
                comment_time = dt.datetime.utcfromtimestamp(comment.created_utc)
                if comment_time >= start_time_utc:
                    comment_author = comment.author.name if comment.author else "[deleted]"
                    writer.writerow({
                        "type": "comment",
                        "id": comment.id,
                        "created_utc": comment.created_utc,
                        "author": comment_author,
                        "body": comment.body,
                    })
        except Exception as e:
            print(f"处理{submission.id}时出错: {str(e)}")

关键修复点说明

  1. 替换帖子获取方式:用subreddit.new(time_filter="week")替代无效的search(query=None),直接获取子版块最近一周的最新帖子,匹配需求。
  2. 统一时区:所有时间计算和比较都使用UTC时区,避免本地时间与UTC时间的差异导致过滤错误。
  3. 增加空作者判断:当作者账号被删除时,用[deleted]替代直接调用.name,防止异常中断数据写入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:17:19