推荐学习书目
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
Topmax
V2EX  ›  Python

在 Python 处理编码后显示到网页上出了点问题

  •  
  •   Topmax · Aug 14, 2018 · 2628 views
    This topic created in 2854 days ago, the information mentioned may be changed or developed.
    首先我获取到了一个 gb2312 编码的网站部分内容 r,
    如果直接 r.encode("gb2312")是可以在 ansi 的编码的网页上正常显示的。
    但是我换了种方式,不用上面那个,直接 html.unescape ( r ),发现没有显性变化,
    在 utf-8 网页上源码是转义的,比如&lt;tr&gt; 显示的是<tr>,
    请问是出了什么问题,我该如何处理数据显示在 utf-8 的网页上。
    第一次接触 python 的 web 应用,麻烦大家了!
    12 replies    2018-08-15 09:55:59 +08:00
    ClutchBear
        1
    ClutchBear  
       Aug 14, 2018
    如果是 requests 获取的,
    res.encoding = res.apparent_encoding
    就行了
    Topmax
        2
    Topmax  
    OP
       Aug 14, 2018
    @ClutchBear 不行呀,到 web 上显示的源码还是&gt;这种转义的
    imn1
        3
    imn1  
       Aug 14, 2018
    问题就出在 html.unescape,这个就是转义啊
    Topmax
        4
    Topmax  
    OP
       Aug 14, 2018
    @imn1 这个 html.unescape 是反转义,原来传过来的就是转义的,现在用反转义,结果和不用 html.unescape 显示的一样。
    imn1
        5
    imn1  
       Aug 14, 2018
    给个例子,说明编码,以及期望显示和编码
    likuku
        6
    likuku  
       Aug 14, 2018 via iPhone
    这是在作爬虫 /内容聚合吧?要是内容都自己从零生产,那么全栈使用 UTF-8 了事
    Topmax
        7
    Topmax  
    OP
       Aug 14, 2018
    @ClutchBear
    @imn1
    @imn1
    @likuku 爬取的内容为 b ‘&#39;\r\n\t\t\t\t\t\t\t\t&lt;TD&gt;’这样的,需要显示到 en,utf-8 的网页上
    imn1
        8
    imn1  
       Aug 14, 2018
    内容是 bytes,你要先 decode
    unecape(这里是 str),没有报错么?
    Topmax
        9
    Topmax  
    OP
       Aug 14, 2018
    @imn1 是这样的
    r = res.encode("gb2312")
    info = html.unescape(r)
    return render.model(info)
    这样写才报错 a bytes-like object is required, not 'str',
    去掉 encode("gb2312") 就不会报错,但&lt;tr&gt;这类应该转义回去的没转义
    imn1
        10
    imn1  
       Aug 14, 2018
    你逐行 print 结果把,我也不知道你这个 render.model 干了什么
    print(info)
    Topmax
        11
    Topmax  
    OP
       Aug 15, 2018
    @imn1 print 出来就是&lt;tr&gt;这种没转义的
    Topmax
        12
    Topmax  
    OP
       Aug 15, 2018
    @imn1 直接 print(infoi)出来的就是<tr>这种正常的,问题应该处在 render,这是 web.py 的模板函数
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2838 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 09:03 · PVG 17:03 · LAX 02:03 · JFK 05:03
    ♥ Do have faith in what you're doing.