使用curl在命令列中下載檔案
阿新 • • 發佈:2019-02-02
今天幫同學從一個網站上下載點資料, 但是上面有上百個連結, 一個一個點選下載實在是工作量太大。 於是自己就想找一個命令列下載工具並用Python寫一個簡單的指令碼來替代這些工作。
百度了一下, 找到了curl
curl: curl是利用URL語法在命令列方式下工作的檔案傳輸工具。 [百科:
將來學習了多執行緒, 可以改為多執行緒下載。
最簡單的下載語法:
curl -o [filename] <url>
例如:
Microsoft Windows [版本 6.0.6001] 版權所有 (C) 2006 Microsoft Corporation。保留所有權利。 C:\Windows\system32>curl -o E:\MIT_BIH_Arrhythmia_Database\103.dat http://physionet.org/physiobank/database/mitdb/103.dat % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 1 1904k 1 23082 0 0 3582 0 0:09:04 0:00:06 0:08:58 3556
這樣子就從網頁http://physionet.org/physiobank/database/mitdb/103.dat把檔案103.dat下載到本地E盤E:\MIT_BIH_Arrhythmia_Database\103.dat
curl --head <url>
獲取下載檔案的大小。例如:
C:\Windows\system32>curl --head http://physionet.org/physiobank/database/mitdb/100.atr HTTP/1.1 200 OK Date: Mon, 28 Nov 2011 05:35:46 GMT Server: Apache/2.2.17 (Fedora) Last-Modified: Thu, 30 Jul 1992 01:21:18 GMT ETag: "82c1c18-11ce-287fa5a2e9f80" Accept-Ranges: bytes Content-Length: 4558 Connection: close Content-Type: application/octet-stream
curl --connect-timeout <seconds> <url>
(參考: http://blog.csdn.net/learnhard/article/details/5683703)
連線超時時間設定。
curl -m <seconds> <url>
傳輸資料超時時間設定。 例如:
C:\Windows\system32>curl -o E:\MIT_BIH_Arrhythmia_Database\104.dat -m 20 "http://physionet.org/physiobank/database/mitdb/104.dat" % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 1 1904k 1 20162 0 0 953 0 0:34:06 0:00:21 0:33:45 377 curl: (28) Operation timed out after 20000 milliseconds with 20162 out of 195000 0 bytes received
更多命令請參考:
# !/usr/bin/env python
# Filename: down.py
# download files from http://physionet.org/physiobank/database/mitdb/
import os
home = r"E:\MIT_BIH_Arrhythmia_Database"
fext = [".atr", ".dat", ".hea"]
hurl = r"http://physionet.org/physiobank/database/mitdb/"
for ext in fext:
for index in range(100, 234):
fname = str(index) + ext
fsave = home + os.path.sep + fname
fget = hurl + fname
if False == os.path.isfile(fsave):
command = "curl -o " + fsave + " " + fget
os.system(command)