【问题标题】:python urllib2 urlopen responsepython urllib2 urlopen 响应
【发布时间】:2012-08-18 11:21:26
【问题描述】:

python urllib2 urlopen 响应:

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

预期:

{"token":"mYWmzpunvasAT795niiR"}

【问题讨论】:

    标签: python urllib2 urlopen


    【解决方案1】:

    您需要将生成的类文件对象绑定到一个变量,否则解释器只会通过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>>
    

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

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

    查看返回的标题:

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

    【讨论】:

    • 我有一个问题。如果我不将f 的内容存储到data,而只是执行f.read(),我只会得到一次内容。如果我再次执行f.read(),它会打印一个空字符串。这是为什么呢?
    • @SidharthSamant:因为您已经使用了流中的所有数据 - 它不是由 urllib2 内部存储的。
    【解决方案2】:

    在您致电urlopen后添加以下内容

    print feed.read()
    

    【讨论】:

      【解决方案3】:

      也许您会发现使用requests library 比使用urllib2 更直观。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-11
        • 1970-01-01
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        • 2023-03-18
        相关资源
        最近更新 更多