如何调用liburl2方法?

2024-10-02 22:37:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在调查python urllib2 download size问题。在

虽然RanRag or jterrace建议的方法对我来说很好,但是我想知道如何使用urllib2.Request.get_header方法来实现同样的效果。所以,我尝试了下面这行代码:

>>> import urllib2
>>> req_info = urllib2.Request('http://mirror01.th.ifl.net/releases//precise/ubuntu-12.04-desktop-i386.iso')
>>> req_info.header_items()
[]
>>> req_info.get_header('Content-Length')
>>>

同样,您可以看到get_header没有返回任何内容,header_items也没有返回任何内容。在

那么,使用上述方法的正确方法是什么呢?在


Tags: or方法info内容sizegetrequestdownload
1条回答
网友
1楼 · 发布于 2024-10-02 22:37:06

urllib2.Request类只是“URL请求的抽象”(http://docs.python.org/library/urllib2.html#urllib2.Request),不执行任何实际的数据检索。必须使用urllib2.urlopen检索数据。urlopen要么直接将url作为字符串,要么也可以传递Request对象的实例。在

例如:

>>> req_info = urllib2.urlopen('https://www.google.com/logos/2012/javelin-2012-hp.jpg')
>>> req_info.headers.keys()
['content-length', 'x-xss-protection', 'x-content-type-options', 'expires', 'server', 'last-modified', 'connection', 'cache-control', 'date', 'content-type']
>>> req_info.headers.getheader('Content-Length')
'52741'

相关问题 更多 >