You need to enable JavaScript to run this app. PRAW抓取Reddit数据写入文件报UnicodeEncodeError编码错误怎么解决
优惠活动
大模型
产品
解决方案
定价
更多

PRAW抓取Reddit数据写入文件报UnicodeEncodeError编码错误怎么解决

问题原因

触发报错的核心原因如下:

  • Windows系统下调用open()函数打开文本文件时,默认使用系统自带的cp1252编码,该编码仅支持有限的西欧字符,无法兼容Reddit评论里包含的emoji、小语种特殊字符等Unicode字符,写入时就会触发编码错误,本次报错里的\U0001f937就是一个cp1252编码不支持的emoji字符。
  • 现有代码的文件操作逻辑也存在隐患:没有异常兜底机制,一旦中途出现错误会直接终止脚本,已经写入的内容也可能因为文件没有正常关闭出现损坏。

解决方案

方案1:指定UTF-8编码打开文件(推荐)

UTF-8是通用的Unicode编码,可以兼容几乎所有特殊字符,仅需修改打开文件的代码即可:
将原来的data = open('data.txt','w')替换为data = open('data.txt','w', encoding='utf-8')。
另外建议搭配with上下文管理器操作文件,无需手动调用close()方法,哪怕脚本中途报错也会自动关闭文件,避免数据损坏。

方案2:增加错误忽略参数(临时调试用)

如果不需要保留所有特殊字符,仅需要先保证脚本可以正常运行,可以在打开文件时添加错误处理参数,遇到无法编码的字符自动跳过:
data = open('data.txt','w', encoding='cp1252', errors='ignore')
注意该方案会丢失部分特殊字符,不建议正式环境使用

修改后的完整代码

import praw

reddit = praw.Reddit(client_id = 'my_client_id',
                     client_secret = 'my_client_secret',
                     username = 'my_username',
                     password = 'my_password',
                     user_agent = 'my_user_agent')
                    
subreddit = reddit.subreddit('news')
hot_python = subreddit.hot(limit=50)

# 改用with上下文管理器+UTF-8编码打开文件
with open('data.txt','w', encoding='utf-8') as data:
    for submission in hot_python:
        if not submission.stickied:
            print(20*'-')
            print('TITEL: '+ submission.title)
            
            submission.comments.replace_more(limit=0)
            for comment in submission.comments.list():
                print(30*'+')
                print('parent_id:', comment.parent())
                print(comment.body)
                if len(comment.replies) > 0:
                    for reply in comment.replies:
                        print('REPLY:')
                        print("\t"+reply.body)
                        print(reply.parent())
        
                data.writelines('parent_id: '+ str(comment.parent()) + 'body: '+ str(comment.body) + "\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:51:02