【问题标题】:How to fix "latin-1 codec can't encode characters in position" in requests如何修复请求中的“latin-1 编解码器无法在位置编码字符”
【发布时间】:2019-12-09 09:58:54
【问题描述】:

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

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.

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

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)

python 版本是一样的。不知道怎么回事。

我该如何解决?

【问题讨论】:

  • 两台机器在命令提示符下locale的输出是什么?有什么不同吗?
  • LANG=en_US.UTF-8 LC_CTYPE="en_US.UTF-8" LC_NUMERIC=ru_RU.UTF-8 LC_TIME=ru_RU.UTF-8 LC_COLLATE="en_US.UTF-8" LC_MONETARY=ru_RU .UTF-8 LC_MESSAGES="en_US.UTF-8" LC_PAPER=ru_RU.UTF-8 LC_NAME=ru_RU.UTF-8 LC_ADDRESS=ru_RU.UTF-8 LC_TELEPHONE=ru_RU.UTF-8 LC_MEASUREMENT=ru_RU.UTF-8 LC_IDENTIFICATION= ru_RU.UTF-8 LC_ALL=
  • 这些语言环境是相同的@Joachim Isaksson

标签: python python-3.x python-requests python-unicode


【解决方案1】:

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

看来您的 PC 设置了 UTF-8C 区域设置,而您的 VPS 使用 latin-1

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

import sys
import locale

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

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

【讨论】:

  • 谢谢,当我添加 PYTHONUTF8=1 时,一切都开始工作了
  • 我的脚本可以在命令行上运行,但不能在 cron 中运行。使用您的指示找到的解决方案是在我的 crontab 中将 LANG="en_US" 更改为 LANG="en_US.utf8"。干杯! :-)
  • 如何添加PYTHONUTF8=1?你添加的是哪个文件?
  • @Nguaial 是一个环境变量。如何设置取决于您使用的操作系统。
  • @AstroFloyd UTF-8 语言环境可能会丢失,在这种情况下,在 Linux 下您必须首先通过 locale-gen en_US.utf8 生成它。您需要管理员权限才能运行此命令。
猜你喜欢
  • 2012-01-07
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多