1

Is there a way to stop downloading from a URL after a certain of bytes have been received?

In PHP there is:

$contents = @file_get_contents($page, FALSE, NULL, 0, 40000);

The fifth argument tells file_get_contents to stop downloading after 40000 bytes. I'm basically looking for something similar in Python. A search on Google and reading docs didn't yield anything. Help would be great, I'm new to Python.

Thanks.

4

2 回答 2

5

urllib

如果您正在使用urllib.urlopen

>>> import urllib
>>> u = urllib.urlopen('http://stackoverflow.com')
>>> x = u.read(1000)
>>> len(x)
1000
>>> u.close()

urllib.urlopen返回类文件对象;您可以指定要下载的字节数。

要求

>>> import requests 
>>> r = requests.get('http://stackoverflow.com', stream=True) 
>>> x = next(r.iter_content(1000), '')[:1000] # iter_content() could yield more than requested; need [:1000]
>>> len(x) 
1000
于 2013-08-20T09:00:51.860 回答
0

我不是 python 专业人士,但这似乎可以完成这项工作:

 req = urllib2.urlopen(url)
 CHUNK = 4000
 chunk = req.read(CHUNK)
于 2013-08-20T09:05:13.470 回答