【发布时间】:2014-06-22 13:24:11
【问题描述】:
是否可以知道 pdf 的大小,例如http://example.com/ABC.pdf 在 python 中使用 requests 模块而不实际下载它。 我正在编写一个应用程序,如果互联网速度很慢并且 pdf 的大小很大,那么它将推迟下载以供将来使用
【问题讨论】:
标签: python http-headers request
是否可以知道 pdf 的大小,例如http://example.com/ABC.pdf 在 python 中使用 requests 模块而不实际下载它。 我正在编写一个应用程序,如果互联网速度很慢并且 pdf 的大小很大,那么它将推迟下载以供将来使用
【问题讨论】:
标签: python http-headers request
响应应在标题中提供要下载的文件的更多详细信息,而无需获取完整文件。
>>> url = "http://www.pdf995.com/samples/pdf.pdf"
>>> req = requests.head(url)
>>> req.content
''
>>> req.headers["content-length"]
'433994'
>>> req = requests.get(url, stream=True)
>>> res = req.iter_content(30)
>>> res
<generator object generate at 0x7f9ad3270320>
>>> res.next()
'%PDF-1.3\n%\xc7\xec\x8f\xa2\n30 0 obj\n<</Len'
>>> res.next()
'gth 31 0 R/Filter /FlateDecode'
>>> res.next()
'>>\nstream\nx\x9c\xed}\xdd\x93%\xb7m\xef\xfb\xfc\x15S\xf7%NU\xf6\xb8'
然后您可以从初始 pdf 文件字节解码 pdf 大小并决定是否继续。
HTTP 只允许请求检索字节范围。
如果您的服务器支持,您可以使用一个技巧,您要求提供仅适用于太大文件的字节范围。如果你得到一些字节(并且状态是好的),你就知道,文件太大了。
如果你得到一个异常ChunkedEncodingError: IncompleteRead(0 bytes read),那么你知道,文件变小了。
这样称呼它:
>>> headers = {"Range": "bytes=999500-999600"}
>>> req = requests.get(url, headers=headers)
这只有在您的服务器允许提供部分内容时才有效。
【讨论】:
stream 参数(获取、发布,无论返回pdf)。
这样
import urllib2
response = urllib2.urlopen('http://example.com/ABC.pdf')
size_of_pdf = response.headers['Content-Length']
在调用response.read()之前,不会下载内容。
看看Response Headers中的Wikipedia
...
Content-Length The length of the response body in octets (8-bit bytes) Content-Length: 348 Permanent
...
OP 要求使用requests,所以@JanVlcinsky 的回答更合适。
【讨论】:
requests 模块。