python 下载文件的几种方式分享
作者:虎卫兵 时间:2021-03-27 14:08:17
目录
1 、一般同步下载
2、 使用流式请求,requests.get方法的stream
3 、异步下载文件
4、 异步拆分下载文件
5、注意
1 、一般同步下载
示例代码:
import requests
import os
def downlaod(url, file_path):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Firefox/68.0"
}
r = requests.get(url=url, headers=headers)
with open(file_path, "wb") as f:
f.write(r.content)
f.flush()
2、 使用流式请求,requests.get方法的stream
默认情况下是stream的值为false,它会立即开始下载文件并存放到内存当中,倘若文件过大就会导致内存不足的情况,程序就会报错。
当把get函数的stream参数设置成True时,它不会立即开始下载,当你使用iter_content或iter_lines遍历内容或访问内容属性时才开始下载,需要注意一点:文件没有下载之前,它也需要保持连接。
iter_content:一块一块的遍历要下载的内容
iter_lines:一行一行的遍历要下载的内容
使用上面两个函数下载大文件可以防止占用过多的内存,因为每次只下载小部分数据。
示例代码:
3 、异步下载文件
由于request的请求是阻塞式的,所以要用aiohttp模块来发起请求。
示例代码:
import aiohttp
import asyncio
import os
async def handler(url, file_path):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Firefox/68.0"
}
async with aiohttp.ClientSession() as session:
r = await session.get(url=url, headers=headers)
with open(file_path, "wb") as f:
f.write(await r.read())
f.flush()
os.fsync(f.fileno())
loop = asyncio.get_event_loop()
loop.run_until_complete(handler(url, file_path))
4、 异步拆分下载文件
上面用的是一个协程下载一个文件,下面的方法是将文件分成几部分,每个部分用一个协程下载,最后再写入文件。
下面这个例子用的是流式写入,即把内容写入到磁盘里面。
import aiohttp
import asyncio
import time
import os
async def consumer(queue):
option = await queue.get()
start = option["start"]
end = option["end"]
url = option["url"]
filename = option["filename"]
i = option["i"]
print(f"第{i}个任务开始运行")
async with aiohttp.ClientSession() as session:
headers = {"Range": f"bytes={start}-{end}"}
r = await session.get(url=url, headers=headers)
with open(filename, "rb+") as f:
f.seek(start)
while True:
chunk = await r.content.read(end - start)
if not chunk:
break
f.write(chunk)
f.flush()
os.fsync(f.fileno())
print(f"第{i}个任务正在写入中ing")
queue.task_done()
print(f"第{i}个任务写入成功")
async def producer(url, headers, filename, queue, coro_num):
async with aiohttp.ClientSession() as session:
resp = await session.head(url=url, headers=headers)
file_size = int(resp.headers["content-length"])
# 创建一个文件
with open(filename, "wb") as f:
pass
part = file_size // coro_num
for i in range(coro_num):
start = part * i
if i == coro_num - 1:
end = file_size
else:
end = start + part
info = {
"start": start,
"end": end,
"url": url,
"filename": filename,
"i": i,
}
queue.put_nowait(info)
async def main():
# 需要填的有url,filename,coro_num
url = ""
filename = ""
coro_num = 0
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Firefox/68.0"
}
queue = asyncio.Queue(coro_num)
await producer(url, headers, filename, queue, coro_num)
task_list = []
for i in range(coro_num):
task = asyncio.create_task(consumer(queue))
task_list.append(task)
await queue.join()
for i in task_list:
i.cancel()
await asyncio.gather(*task_list)
startt = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
end = time.time() - startt
print(f"用了{end}秒")
5、注意
以上的示例都是介绍思路,程序并不健壮,健壮的程序需要加入错误捕获和错误处理。
来源:https://www.cnblogs.com/NEGAN-H/p/14617598.html
标签:python,下载,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SQL提供的进行数据传输的实用程序—BCP
2009-01-23 13:45:00
关于document.cookie的使用
2008-03-25 12:07:00
Django框架设置cookies与获取cookies操作详解
2021-07-24 09:10:49
![](https://img.aspxhome.com/file/2023/1/87961_0s.png)
Python中如何使用if语句处理列表实例代码
2023-11-01 03:12:46
![](https://img.aspxhome.com/file/2023/0/79590_0s.png)
将python代码和注释分离的方法
2022-04-06 12:04:50
centos6.7安装python2.7.11的具体方法
2022-04-29 00:42:54
细化解析:SQL Server数据库的集群设计
2009-02-05 15:59:00
python重要函数eval多种用法解析
2023-02-08 20:16:46
一个可应用在ASP 标记加密文件的MD5的DLL组件
2008-04-12 07:21:00
Python实现的序列化和反序列化二叉树算法示例
2021-06-11 07:14:23
PHP asXML()函数讲解
2023-06-08 14:04:37
![](https://img.aspxhome.com/file/2023/1/55411_0s.png)
python time.sleep()是睡眠线程还是进程
2022-04-09 17:33:16
简单了解python中的与或非运算
2021-03-20 01:45:02
![](https://img.aspxhome.com/file/2023/5/67915_0s.png)
Python中的左斜杠、右斜杠(正斜杠和反斜杠)
2022-02-08 07:00:34
python提效小工具之统计xmind用例数量(源码)
2021-11-26 21:42:44
![](https://img.aspxhome.com/file/2023/6/72246_0s.png)
php中in_array函数用法探究
2023-06-21 21:03:54
ORACLE 10g 安装教程[图文]
2009-05-24 19:12:00
![](https://img.aspxhome.com/file/UploadPic/20095/26/200952620153777.jpg)
python 实现删除文件或文件夹实例详解
2021-03-23 03:16:37
asp远程网页数据采集常用函数代码
2008-10-31 12:44:00
Oracle 下医嘱执行函数
2009-03-02 10:49:00