python urllib2 urlopen 响应 [英] python urllib2 urlopen response

查看:42
本文介绍了python urllib2 urlopen 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python urllib2 urlopen 响应:

>

预期:

{"token":"mYWmzpunvasAT795niiR"}

解决方案

您需要将生成的类文件对象绑定到一个变量,否则解释器只会通过 repr 转储它:

<预><代码>>>>导入 urllib2>>>urllib2.urlopen('http://www.google.com')<addinfourl at 18362520 其 fp = <socket._fileobject object at 0x106b250>>>>>>>>f = urllib2.urlopen('http://www.google.com')>>>F<addinfourl at 18635448,其 fp = <socket._fileobject object at 0x106b950>>

要获取实际数据,您需要执行 read().

<预><代码>>>>数据 = f.read()>>>数据[:50]'<!doctype html><html itemscope="itemscope" itemtyp'

查看返回的标题:

<预><代码>>>>打印 f.headers日期:2012 年 8 月 23 日星期四 00:46:22 GMT过期时间:-1缓存控制:私有,最大年龄=0... 等等 ...

python urllib2 urlopen response:

<addinfourl at 1081306700 whose fp = <socket._fileobject object at 0x4073192c>>

expected:

{"token":"mYWmzpunvasAT795niiR"}

解决方案

You need to bind the resultant file-like object to a variable, otherwise the interpreter just dumps it via repr:

>>> import urllib2
>>> urllib2.urlopen('http://www.google.com')
<addinfourl at 18362520 whose fp = <socket._fileobject object at 0x106b250>>
>>> 
>>> f = urllib2.urlopen('http://www.google.com')
>>> f
<addinfourl at 18635448 whose fp = <socket._fileobject object at 0x106b950>>

To get the actual data you need to perform a read().

>>> data = f.read()
>>> data[:50]
'<!doctype html><html itemscope="itemscope" itemtyp'

To see the headers returned:

>>> print f.headers
Date: Thu, 23 Aug 2012 00:46:22 GMT
Expires: -1
Cache-Control: private, max-age=0
... etc ...

这篇关于python urllib2 urlopen 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆