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

请教 request 模块, get url 回来的.text,有非 gbk 码(\xef),无法正常 print...

  •  
  •   uti6770werty · Mar 5, 2021 · 2519 views
    This topic created in 2074 days ago, the information mentioned may be changed or developed.

    在浏览器里看到"content="text/html; charset=utf-8"
    request 获取回来的对象,用.encoding 看到是:ISO-8859-1
    看到网上的例子,可能用的环境都是 Python2 的时代,str 还有.decode()方法
    似乎没能找到合适的方法。。。
    于是自己试着摸了一下,未能完成,

    s = requests.get(link, headers=headd)
    htmlCode = (s.text).encode("ISO-8859-1")).decode("utf-8")# 失败
    

    发帖请教各位,谢谢!

    8 replies  •  2021-03-06 14:23:41 +08:00
    datou
    datou
    Mar 5, 2021❤️1
    1
    第二行的 s.text 改成 s.content
    ysc3839
    ysc3839
    Mar 5, 2021 via Android
    2
    或者先修改 r.encoding,再用 r.text 读取。
    https://2.python-requests.org/zh_CN/latest/user/quickstart.html#id3
    imn1
    imn1
    Mar 5, 2021
    3
    从 bytes 类型就是.content 直接使用 decode,不要从 str 类型 encode+decode

    如果你要全文,甚至整个 html,再去研究具体编码
    如果只是抓取部分,decode 时忽略不兼容字符就行了(error 参数)
    不要纠结在无关问题上,忽略的字符恰好在你要抓取的内容之中概率极低
    zhuweiyou
    zhuweiyou
    Mar 5, 2021
    4
    虽然不写 py .

    但是这种情况在别的语言里, 一般是先拿到 buffer / bytes 转编码, 而不是先转成 string 再转编码.
    wzb0909
    wzb0909
    Mar 5, 2021 via iPhone
    5
    @zhuweiyou 虽然已经不写 py 。

    但是 requests 这个库集成了各种方便操作,如果经常使用,看一下文档掌握了各种用法会更好。
    ysc3839
    ysc3839
    Mar 5, 2021 via Android
    6
    @imn1 楼主的情况应该是服务器没在 HTTP 头里指定编码,而是在 html 里用 meta charset 指定了。但是 requests 并没有解析 html 的功能,于是使用默认编码 ISO-8859-1 进行解码。
    这种情况下,忽略的字符很可能是需要抓取的内容,比如网页使用 UTF-8 编码,主要内容是中文,当作 ISO-8859-1 解码的话,中文部分都是无效的。
    omph
    omph
    Mar 5, 2021
    7
    Python3 使用 Requests 抓取网页乱码
    https://my.oschina.net/u/1044667/blog/898900
    Kobayashi
    Kobayashi
    Mar 6, 2021
    8
    Encoding 猜测错误,很正常。

    Response.text 其实就是 Response.content decode() 而来。其编码来源:1) Response.encoding 来自于 resp header 。如果前者为空,2) Response.apparent_encoding,利用 chardet.detect 猜测获得。

    多半是响应头没有 encoding,然后使用 chardet 猜测错误。chardet 并不是 100% 准确。

    解决方案:

    - 设置正确 Response.encoding 后再读取 Response.text
    - 或者直接 Response.content.decode(you_encoding)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3973 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 07:13 · PVG 15:13 · LAX 23:13 · JFK 02:13
    ♥ Do have faith in what you're doing.