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
h19981126g
V2EX  ›  Python

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

  •  
  •   h19981126g · 2018-08-14 15:37:03 +08:00 · 2092 次点击
    这是一个创建于 2075 天前的主题,其中的信息可能已经有所发展或是发生改变。
    首先我获取到了一个 gb2312 编码的网站部分内容 r,
    如果直接 r.encode("gb2312")是可以在 ansi 的编码的网页上正常显示的。
    但是我换了种方式,不用上面那个,直接 html.unescape ( r ),发现没有显性变化,
    在 utf-8 网页上源码是转义的,比如&lt;tr&gt; 显示的是<tr>,
    请问是出了什么问题,我该如何处理数据显示在 utf-8 的网页上。
    第一次接触 python 的 web 应用,麻烦大家了!
    12 条回复    2018-08-15 09:55:59 +08:00
    ClutchBear
        1
    ClutchBear  
       2018-08-14 15:45:09 +08:00
    如果是 requests 获取的,
    res.encoding = res.apparent_encoding
    就行了
    h19981126g
        2
    h19981126g  
    OP
       2018-08-14 16:31:25 +08:00
    @ClutchBear 不行呀,到 web 上显示的源码还是&gt;这种转义的
    imn1
        3
    imn1  
       2018-08-14 16:53:16 +08:00
    问题就出在 html.unescape,这个就是转义啊
    h19981126g
        4
    h19981126g  
    OP
       2018-08-14 17:02:11 +08:00
    @imn1 这个 html.unescape 是反转义,原来传过来的就是转义的,现在用反转义,结果和不用 html.unescape 显示的一样。
    imn1
        5
    imn1  
       2018-08-14 18:07:50 +08:00
    给个例子,说明编码,以及期望显示和编码
    likuku
        6
    likuku  
       2018-08-14 19:33:33 +08:00 via iPhone
    这是在作爬虫 /内容聚合吧?要是内容都自己从零生产,那么全栈使用 UTF-8 了事
    h19981126g
        7
    h19981126g  
    OP
       2018-08-14 22:06:50 +08:00
    @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  
       2018-08-14 22:44:23 +08:00
    内容是 bytes,你要先 decode
    unecape(这里是 str),没有报错么?
    h19981126g
        9
    h19981126g  
    OP
       2018-08-14 23:10:10 +08:00
    @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  
       2018-08-14 23:54:11 +08:00
    你逐行 print 结果把,我也不知道你这个 render.model 干了什么
    print(info)
    h19981126g
        11
    h19981126g  
    OP
       2018-08-15 09:47:15 +08:00
    @imn1 print 出来就是&lt;tr&gt;这种没转义的
    h19981126g
        12
    h19981126g  
    OP
       2018-08-15 09:55:59 +08:00
    @imn1 直接 print(infoi)出来的就是<tr>这种正常的,问题应该处在 render,这是 web.py 的模板函数
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2948 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 03:09 · PVG 11:09 · LAX 20:09 · JFK 23:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.