面向对象用python写出可断点下载的代码
时间: 2024-05-01 08:19:45 浏览: 72
《python三剑客项目》-外星人入侵游戏,python全代码
下面是一个简单的面向对象的 Python 下载器,可以实现断点续传的功能:
```python
import requests
class Downloader:
def __init__(self, url, chunk_size=1024):
self.url = url
self.chunk_size = chunk_size
self.file_size = int(requests.head(url).headers.get('Content-Length', 0))
self.file_name = url.split('/')[-1]
self.completed = False
def start(self):
headers = {"Range": f"bytes=0-{self.chunk_size}"}
response = requests.get(self.url, headers=headers, stream=True)
with open(self.file_name, 'wb') as f:
f.write(response.content)
while not self.completed:
self.resume()
def resume(self):
headers = {"Range": f"bytes={os.path.getsize(self.file_name)}-{self.file_size}"}
response = requests.get(self.url, headers=headers, stream=True)
with open(self.file_name, 'ab') as f:
for chunk in response.iter_content(chunk_size=self.chunk_size):
if chunk:
f.write(chunk)
if os.path.getsize(self.file_name) == self.file_size:
self.completed = True
```
使用方法:
```python
downloader = Downloader('https://example.com/large_file.zip')
downloader.start()
```
这个下载器会在开始时先下载前 1KB 的数据,然后再按照文件大小分块下载,直到下载完成。如果下载过程中中断,再次运行下载器会自动从上次中断的位置继续下载。
阅读全文