用 requests 模塊從 Web 下載文件
requests 模塊讓你很容易從 Web 下載文件,不必擔心一些復雜的問題,諸如網絡錯誤、連接問題和數據壓縮。requests 模塊不是 Python 自帶的,所以必須先安裝。
requests.get()函數接受一個要下載的 URL 字符串。通過在 requests.get()的返回
值上調用 type(),你可以看到它返回一個 Response 對象,其中包含了 Web 服務器對
你的請求做出的響應。
>>> import requests
>>> res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
>>> type(res)
<class 'requests.models.Response'>
>>> res.status_code == requests.codes.ok
True
>>> len(res.text)
178981
>>> print(res.text[:250])
The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare
This eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever. You may copy it, give it away or
re-use it under the terms of the Proje
該 URL 指向一個文本頁面,其中包含整部羅密歐與朱麗葉,它是由古登堡計
划提供的。 通過檢查 Response 對象的 status_code 屬性, 你可以了解對這個網頁的
請求是否成功。如果該值等於requests.codes.ok,那么一切都好(順便說一下,HTTP
協議中“OK”的狀態碼是 200。你可能已經熟悉404 狀態碼,它表示“沒找到” ) 。
如果請求成功,下載的頁面就作為一個字符串,保存在 Response 對象的 text
變量中。這個變量保存了包含整部戲劇的一個大字符串,調用 len(res.text)表明,
它的長度超過 178000 個字符。最后,調用 print(res.text[:250])顯示前 250 個字符。