Python下載文件的10種方法介紹
在Python中,我們可以使用多種方法來(lái)實(shí)現(xiàn)文件下載功能。本文將介紹10種不同的Python文件下載方式,并提供詳細(xì)的代碼示例。
1. 使用urllib.request模塊
import urllib.request
url = 'https://example.com/file.zip'
filename = 'file.zip'
urllib.request.urlretrieve(url, filename)
print(f"文件已下載到: {filename}")
2. 使用requests庫(kù)(簡(jiǎn)單方式)
import requests
url = 'https://example.com/file.zip'
filename = 'file.zip'
response = requests.get(url)
with open(filename, 'wb') as f:
f.write(response.content)
print("下載完成!")
3. 使用requests庫(kù)(帶進(jìn)度條)
import requests
from tqdm import tqdm
url = 'https://example.com/largefile.zip'
filename = 'largefile.zip'
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
block_size = 1024 # 1KB
progress_bar = tqdm(total=total_size, unit='iB', unit_scale=True)
with open(filename, 'wb') as f:
for data in response.iter_content(block_size):
progress_bar.update(len(data))
f.write(data)
progress_bar.close()
print("\n下載完成!")
4. 使用wget庫(kù)
import wget
url = 'https://example.com/file.zip'
filename = wget.download(url)
print(f"\n文件已下載到: {filename}")
5. 使用http.client(標(biāo)準(zhǔn)庫(kù))
import http.client
import urllib.parse
url = 'https://example.com/file.zip'
parsed_url = urllib.parse.urlparse(url)
filename = 'file.zip'
conn = http.client.HTTPSConnection(parsed_url.netloc)
conn.request("GET", parsed_url.path)
response = conn.getresponse()
with open(filename, 'wb') as f:
f.write(response.read())
conn.close()
print("下載完成!")
6. 使用aiohttp(異步下載)
import aiohttp
import asyncio
async def download_file(url, filename):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
with open(filename, 'wb') as f:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
f.write(chunk)
print(f"文件已下載到: {filename}")
url = 'https://example.com/file.zip'
filename = 'file.zip'
???????asyncio.run(download_file(url, filename))7. 使用pycurl(高性能下載)
import pycurl
from io import BytesIO
url = 'https://example.com/file.zip'
filename = 'file.zip'
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.WRITEDATA, buffer)
c.perform()
c.close()
with open(filename, 'wb') as f:
f.write(buffer.getvalue())
print("下載完成!")
8. 使用urllib3庫(kù)
import urllib3
url = 'https://example.com/file.zip'
filename = 'file.zip'
http = urllib3.PoolManager()
response = http.request('GET', url)
with open(filename, 'wb') as f:
f.write(response.data)
print("下載完成!")
9. 使用ftplib下載FTP文件
from ftplib import FTP
ftp = FTP('ftp.example.com')
ftp.login(user='username', passwd='password')
filename = 'remote_file.zip'
local_filename = 'local_file.zip'
with open(local_filename, 'wb') as f:
ftp.retrbinary(f'RETR {filename}', f.write)
ftp.quit()
print("FTP文件下載完成!")
10. 使用scp下載(通過(guò)paramiko)
import paramiko
host = 'example.com'
port = 22
username = 'user'
password = 'password'
remote_path = '/path/to/remote/file.zip'
local_path = 'file.zip'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
sftp = ssh.open_sftp()
sftp.get(remote_path, local_path)
sftp.close()
ssh.close()
print("SCP文件下載完成!")
總結(jié)
本文介紹了10種Python下載文件的方法,包括:
- 1.urllib.request標(biāo)準(zhǔn)庫(kù)方法
- 2.requests庫(kù)簡(jiǎn)單方法
- 3.requests庫(kù)帶進(jìn)度條方法
- 4.wget庫(kù)專(zhuān)用方法
- 5.http.client標(biāo)準(zhǔn)庫(kù)方法
- 6.aiohttp異步方法
- 7.pycurl高性能方法
- 8.urllib3庫(kù)方法
- 9.ftplib FTP下載
- 10.paramiko SCP下載
根據(jù)不同的需求和場(chǎng)景,可以選擇最適合的方法。對(duì)于簡(jiǎn)單的下載任務(wù),requests庫(kù)是最方便的選擇;對(duì)于大文件下載,帶進(jìn)度條的requests或異步aiohttp更合適;而對(duì)于特殊協(xié)議如FTP/SCP,則需要使用專(zhuān)門(mén)的庫(kù)。
到此這篇關(guān)于Python下載文件的10種方法介紹的文章就介紹到這了,更多相關(guān)Python下載文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何使用 Pylint 來(lái)規(guī)范 Python 代碼風(fēng)格(來(lái)自IBM)
本文通過(guò)詳細(xì)的理論介紹和簡(jiǎn)單易懂的實(shí)例全面介紹了 Python 代碼分析工具 Pylint。相信讀者看完后一定可以輕松地將 Pylint 運(yùn)用到自己的開(kāi)發(fā)工程中2018-04-04
五分鐘學(xué)會(huì)怎么用Pygame做一個(gè)簡(jiǎn)單的貪吃蛇
這篇文章主要介紹了五分鐘學(xué)會(huì)怎么用Pygame做一個(gè)簡(jiǎn)單的貪吃蛇,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-01-01
Python實(shí)現(xiàn)多張圖片合成一張馬賽克圖片
這篇文章主要介紹了了Python如何實(shí)現(xiàn)將多張圖片合成一張馬賽克圖片。文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Python有一定的幫助,感興趣的可以學(xué)習(xí)一下2021-12-12
Python迭代器協(xié)議及for循環(huán)工作機(jī)制詳解
這篇文章主要介紹了Python迭代器協(xié)議及for循環(huán)工作機(jī)制詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
Python讀寫(xiě)文件模式和文件對(duì)象方法實(shí)例詳解
這篇文章主要介紹了Python讀寫(xiě)文件模式和文件對(duì)象方法,結(jié)合實(shí)例形式詳細(xì)分析了Python文件操作常用技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-09-09
Pytest使用fixture實(shí)現(xiàn)token共享的方法
同學(xué)們?cè)谧鰌ytest接口自動(dòng)化時(shí),會(huì)遇到一個(gè)場(chǎng)景就是不同的測(cè)試用例需要有一個(gè)登錄的前置步驟,登錄完成后會(huì)獲取到token,用于之后的代碼中,本文給大家介紹Pytest使用fixture實(shí)現(xiàn)token共享的方法,感興趣的朋友一起看看吧2023-11-11

