V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Cheez
V2EX  ›  Python

解决 Python print 输出文本显示 gbk 编码错误

  •  
  •   Cheez · 2018-07-14 16:33:32 +08:00 · 2843 次点击
    这是一个创建于 2106 天前的主题,其中的信息可能已经有所发展或是发生改变。

    前阵子想爬点东西,结果 sublime 3 一直提示错误UnicodeEncodeError: ‘ gbk ’ codec can ’ t encode character ‘\xa0 ’ in position,在网上一查,发现是 Windows 的控制台的问题。控制台的编码是 GBK,Python 是 UTF-8,造成了冲突。

    下面给出三种解决方法:

    第一种方法:直接替换出错的内容

    url = 'https://zhuanlan.zhihu.com/p/39747259' 
    print(requests.get(url).text.replace('\xa0', ' '))```
    
    # 第二种方法:再解码
    
    先用 GBK 编码,加个 ignore 丢弃错误的字符,然后再解码。
    
    ```import requests
    url = 'https://zhuanlan.zhihu.com/p/39747259'
    print(requests.get(url).text.encode('gbk', 'ignore').decode('gbk')```
    
    # 第三种方法:修改控制台编码
    
    新建一个 cmd.reg, 输入代码:
    
    ```Windows Registry Editor Version 5.00
    [HKEY_CURRENT_USER\Console\%SystemRoot%_system32_cmd.exe]
    "CodePage"=dword:0000fde9
    "FontFamily"=dword:00000036
    "FontWeight"=dword:00000190
    "FaceName"="Consolas"
    "ScreenBufferSize"=dword:232900d2
    "WindowSize"=dword:002b00d2```
    
    保存后运行。如果 Ctrl+B 无效,用 python.exe 打开.py 程序后再试一次。
    
    最后硬广一波,新开了个 Python 专栏,请大家多捧捧场
    https://zhuanlan.zhihu.com/cheezpython
    https://segmentfault.com/blog/cheez_python
    
    3 条回复    2018-07-15 09:00:55 +08:00
    ysc3839
        1
    ysc3839  
       2018-07-14 17:21:47 +08:00 via Android
    没必要改注册表,用 SetConsoleCP 可以直接更改控制台的 codepage。
    https://docs.microsoft.com/en-us/windows/console/setconsolecp
    Cheez
        2
    Cheez  
    OP
       2018-07-14 21:43:00 +08:00 via Android
    格式居然乱了。。。。
    mingyun
        3
    mingyun  
       2018-07-15 09:00:55 +08:00   ❤️ 1
    requests 还得加 header 吧

    <html>
    <head><title>400 Bad Request</title></head>
    <body bgcolor="white">
    <center><h1>400 Bad Request</h1></center>
    <hr><center>openresty</center>
    </body>
    </html>
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   894 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 21:14 · PVG 05:14 · LAX 14:14 · JFK 17:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.