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

求大佬帮我看看我这个用 urlopen().read()获取的 bytes 串是不是有问题啊

  •  1
     
  •   grimpil · 2017-03-23 21:10:19 +08:00 · 2175 次点击
    这是一个创建于 2597 天前的主题,其中的信息可能已经有所发展或是发生改变。

    之前偶然发现了这样一个页面,
    http://www.angio.net/pi/
    可以用来查找任意一串数字在圆周率小数点后两亿位中的具体位置,感觉还挺好玩的
    然后我找到了它的请求接口
    http://www.angio.net/newpi/piquery?q=666666666

    如果在浏览器里直接输入上面的 url ,可以得到下面的 json
    {"et":66874,"r":[{"k":"666666666","st":0,"status":"found","p":45681781,"db":"86731050497515079094","da":"71734856294979983444","c":1}],"status":"OK"}
    这是正常的

    但是如果使用下面代码获取:

    url = 'http://www.angio.net/newpi/piquery?q=666666666'
    #这里 headers 是完全复制了浏览器里的
    req = urllib.request.Request(url, None, headers)
    response = urllib.request.urlopen(req).read()
    

    最终 response 的值为:

    b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03L\x8c1\x0e\xc20\x10\xc0\xfe\xe29C\x8e\r\xb9\xfb\x02\x03\x0f@\x0c\x85\xc2\x82\x04\x88\xb6S\xc5\xdfQ\x07$\xbcx\xb0\xe4\x95\xebL45)\x897q\\xb9\x13\xb4\x1f$\xa6\x99\xc8\x9b\x86y\x99\x08n\xcf\xe51\x92x\x11Z[\x17\xeb\x92\x18\xcf\x04\xbdY\x91\\xb3\xbaU\xa9\xd9<\xbb\x92\x18\x07\x02\x13+\xdak\xdb\xb9\xba\xb9\xf7\xa2\xba\xb5\x0b!\x9f\xd3\xdf\xfd\xb0\xe7\x0b\x00\x00\xff\xff\xaa\x05\x00\x00\x00\xff\xff\x03\x00B\xb8\x0e\x84\x95\x00\x00\x00'

    此时如果对 response 执行 decode('utf-8')会报错。

    仔细一看,这个 bytes 串好像不对劲,里面还有特殊符号,正常的 bytes 串不应该这样吧

    请教一下各位,这种情况应该怎么处理,怎么样才能获取到正常的结果

    3 条回复    2017-03-23 22:36:38 +08:00
    weyou
        1
    weyou  
       2017-03-23 21:41:44 +08:00 via Android
    回的 gzip 压缩过的没解压?
    grimpil
        2
    grimpil  
    OP
       2017-03-23 22:26:45 +08:00
    @weyou 还真是这个原因,非常感谢!

    又加了一句解压缩之后就正常了
    gzip.decompress(response).decode("utf-8")
    weyou
        3
    weyou  
       2017-03-23 22:36:38 +08:00 via Android
    @grimpil 其实你没必要自己解压,可以先试试去掉 header 里 Accept-Encoding 的压缩选项,只保留 identity ,服务器应该就会回明文了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1028 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 18:07 · PVG 02:07 · LAX 11:07 · JFK 14:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.