我已经看到很多话题打开这个问题,但他们都没有帮助我解决这个问题。我有一个包含许多不同字符的文本的数据集。因此,我在使用Python 2.7.13上的Requests库进行POST请求之前对文本进行了编码。请求发布UnicodeEncodeError出现,尽管utf-8编码
我的代码如下:
# -*- coding: utf-8 -*-
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
import requests
text = """So happy to be together on your birthday! ❤ Thankful for real life. ❤ A post shared by Jessica Chastain (@jessicachastain) on Nov 13, 2016 at 5:22am PST"""
textX = json.dumps({'text': text.encode('utf-8')})
r = requests.post('http://####', data=textX,
headers={'Content-Type': 'application/json; charset=UTF-8'})
print(r.text)
数据以JSON格式发送。无论我尝试将文本编码为UTF-8,我仍然从请求中收到以下错误。
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2764' in
position 42: Body ('❤') is not valid Latin-1. Use body.encode('utf-8')
if you want to send it encoded in UTF-8.
编辑: 语法错误固定的,但问题
是不是你缺少一个右')''中= textX json.dumps({”文本':text.encode('utf-8'})'?应该是造成语法错误... 你可以发布其余的回溯:哪一行产生UnicodeError? – cowbert
@cowbert,你是对的,但出现语法错误,但即使语法正确,我也得到了Unicode错误。 – Furkanicus