收到特定字节数后停止下载?

Zet*_*ttt 1 python

有没有办法在收到一定的字节后停止从URL下载?

在PHP中有:

$contents = @file_get_contents($page, FALSE, NULL, 0, 40000);
Run Code Online (Sandbox Code Playgroud)

第五个参数告诉file_get_contents在40000字节后停止下载.我基本上在寻找类似Python的东西.在Google上搜索和阅读文档并没有产生任何结果.帮助会很棒,我是Python的新手.

谢谢.

fal*_*tru 5

的urllib

如果您正在使用urllib.urlopen:

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

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
Run Code Online (Sandbox Code Playgroud)