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

如何使用Tweepy解决UnicodeEncodeError编码错误?

解决Tweepy中UnicodeEncodeError的问题

这个错误是因为你的控制台默认编码不支持输出用户信息里的某些Unicode字符(比如特殊表情、非英语字符等)。以下几种方法可以解决:

方法1:修改全局标准输出编码

直接设置Python的标准输出流使用UTF-8编码,这样所有print操作都会用UTF-8输出:

import tweepy
import sys
from api_keys import *

# 配置标准输出为UTF-8编码
sys.stdout.reconfigure(encoding='utf-8')

auth = tweepy.OAuth1UserHandler(
    consumer_key, consumer_secret, access_token, access_token_secret)

api = tweepy.API(auth)

user = api.verify_credentials()
print(user)

方法2:单独处理输出内容的编码

如果你不想修改全局设置,可以将用户信息转为字符串后,手动指定编码输出:

import tweepy
from api_keys import *

auth = tweepy.OAuth1UserHandler(
    consumer_key, consumer_secret, access_token, access_token_secret)

api = tweepy.API(auth)

user = api.verify_credentials()
# 将内容转为UTF-8编码的字符串后打印
print(str(user).encode('utf-8').decode('utf-8'))

或者在print时忽略无法编码的字符(不推荐,会丢失特殊字符):

print(user, errors='ignore')

方法3:将内容写入UTF-8编码的文件

如果需要完整保留所有字符,可以把用户信息写入文件而非控制台:

import tweepy
from api_keys import *

auth = tweepy.OAuth1UserHandler(
    consumer_key, consumer_secret, access_token, access_token_secret)

api = tweepy.API(auth)

user = api.verify_credentials()
# 写入UTF-8编码的文件
with open('user_credentials.txt', 'w', encoding='utf-8') as file:
    file.write(str(user))

你之前用的encoding('utf-8')通常是在文件读写时指定,这里因为是控制台输出编码的问题,所以需要针对输出流或者输出内容做编码处理,上面的方法可以对应你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:45:56