如何修复“latin-1 编解码器无法对位置中的字符进行编码";在请求中 [英] How to fix "latin-1 codec can't encode characters in position" in requests

查看:73
本文介绍了如何修复“latin-1 编解码器无法对位置中的字符进行编码";在请求中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 3 中编码时遇到问题.当我在我的 PC 上进行测试时,我没有发现任何错误:

Python 3.7.3(默认,2019 年 6 月 24 日,04:54:02)[GCC 9.1.0] 在 Linux 上输入帮助"、版权"、信用"或许可"以获取更多信息.>>>进口请求>>>打印(requests.get('https://www.kinopoisk.ru').文本)一切安好.

但是当我在 VPS 上运行此代码时出现以下错误:

Python 3.7.3(默认,2019 年 4 月 3 日,19:16:38)[GCC 8.0.1 20180414(实验性)[主干修订版 259383]] 在 linux 上输入帮助"、版权"、信用"或许可"以获取更多信息.>>>进口请求>>>打印(requests.get('https://www.kinopoisk.ru').文本)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>UnicodeEncodeError: 'latin-1' 编解码器无法对位置 393-401 中的字符进行编码:序号不在范围内 (256)

python 版本是一样的.我不知道发生了什么.

我该如何解决?

解决方案

如果您的环境使用 C os POSIX 语言环境,根据 pep-538,Python 3.7 会自动将其强制转换为 UTF-8 感知语言环境.

因此您的 PC 似乎具有 UTF-8C 语言环境集,而您的 VPS 使用 latin-1.

尝试在两台机器上的交互式 Python 会话中运行以下命令:

导入系统导入语言环境打印(sys.getfilesystemencoding())打印(locale.getpreferredencoding())

如果您不想更改 VPS 上的区域设置,您可以在其环境中设置 PYTHONUTF8=1,或者您可以使用 -X utf-8使用 Python 的选项.

I am having trouble with encoding in python 3. When I was testing on my PC I get no errors:

Python 3.7.3 (default, Jun 24 2019, 04:54:02) 
[GCC 9.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> print(requests.get('https://www.kinopoisk.ru').text)

everything good.

But when I ran this code on my VPS a have following error:

Python 3.7.3 (default, Apr  3 2019, 19:16:38) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import requests
>>> print(requests.get('https://www.kinopoisk.ru').text) 

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 393-401: ordinal not in range(256)

The python versions are the same. I don't know what is going on.

How do I fix it?

解决方案

If your environment uses the C os POSIX locale, Python 3.7 automatically coerces that to a UTF-8 aware locale, according to pep-538.

So it seems that your PC has an UTF-8 or C locale set, while your VPS uses latin-1.

Try running the following in an interactive Python session on both machines:

import sys
import locale

print(sys.getfilesystemencoding())
print(locale.getpreferredencoding())

It you do not want to change the locale on your VPS, you could set PYTHONUTF8=1 in its environment, or you could use the -X utf-8 option with Python.

这篇关于如何修复“latin-1 编解码器无法对位置中的字符进行编码";在请求中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆