用法:
urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)
將由 URL 表示的網絡對象複製到本地文件。如果 URL 指向本地文件,除非提供文件名,否則不會複製對象。返回一個元組
(filename, headers)
,其中filename
是可以在其中找到對象的本地文件名,而headers
是urlopen()
返回的對象的info()
方法(對於遠程對象)。例外情況與urlopen()
相同。第二個參數(如果存在)指定要複製到的文件位置(如果不存在,則該位置將是具有生成名稱的臨時文件)。第三個參數(如果存在)是可調用的,將在建立網絡連接時調用一次,然後在每個塊讀取之後調用一次。可調用對象將傳遞三個參數;到目前為止傳輸的塊數,以字節為單位的塊大小以及文件的總大小。第三個參數可能是舊 FTP 服務器上的
-1
,它不會返回文件大小以響應檢索請求。以下示例說明了最常見的使用場景:
>>> import urllib.request >>> local_filename, headers = urllib.request.urlretrieve('http://python.org/') >>> html = open(local_filename) >>> html.close()
如果
url
使用http:
方案標識符,則可以給出可選的data
參數來指定POST
請求(通常請求類型是GET
)。data
參數必須是標準application/x-www-form-urlencoded
格式的字節對象;請參閱urllib.parse.urlencode()
函數。當
urlretrieve()
檢測到可用數據量小於預期量(即Content-Length
標頭報告的大小)時,將引發ContentTooShortError
。例如,當下載中斷時,可能會發生這種情況。Content-Length
被視為下限:如果要讀取的數據更多,則 urlretrieve 會讀取更多數據,但如果可用數據更少,則會引發異常。在這種情況下,您仍然可以檢索下載的數據,它存儲在異常實例的
content
屬性中。如果沒有提供
Content-Length
標頭,則 urlretrieve 無法檢查它已下載的數據的大小,而隻是將其返回。在這種情況下,您隻需假設下載成功。
相關用法
- Python urllib.parse.urlparse用法及代碼示例
- Python urllib.parse.urljoin用法及代碼示例
- Python urllib.parse.urllib.parse.SplitResult.geturl用法及代碼示例
- Python unittest.mock.AsyncMock.assert_awaited_once_with用法及代碼示例
- Python unittest.TestCase.assertWarnsRegex用法及代碼示例
- Python unittest.mock.Mock.reset_mock用法及代碼示例
- Python unittest.mock.Mock.__class__用法及代碼示例
- Python unittest.mock.Mock.call_args用法及代碼示例
- Python unittest.TestCase.assertRaisesRegex用法及代碼示例
- Python unittest.mock.call用法及代碼示例
- Python unittest.mock.Mock.method_calls用法及代碼示例
- Python unittest.mock.Mock.call_args_list用法及代碼示例
- Python unittest.mock.AsyncMock.assert_any_await用法及代碼示例
- Python unittest.mock.Mock.assert_called用法及代碼示例
- Python unittest.TestCase.assertRaises用法及代碼示例
- Python unittest.TestCase.tearDownClass用法及代碼示例
- Python unittest.mock.Mock.assert_not_called用法及代碼示例
- Python unittest.IsolatedAsyncioTestCase用法及代碼示例
- Python unittest.TestCase.setUpClass用法及代碼示例
- Python unittest.mock.AsyncMock.await_args_list用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 urllib.request.urlretrieve。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。