Python下載文件處理

在本教程中,您將學習如何使用不同的Python模塊從Web下載文件。 您將下載常規文件,網頁,YouTube視頻,Google網盤文件,Amazon S3其他來源的文件。

此外,您將學習如何克服許多可能遇到的挑戰,例如下載重定向文件,下載大文件,多線程下載和其他策略。

requests

import requests

url = 'https://www.python.org/static/img/[email protected]'
myfile = requests.get(url)
open('PythonImage.png', 'wb').write(myfile.content)

重定向

import requests

url = 'https://readthedocs.org/projects/python-guide/downloads/pdf/latest/'
myfile = requests.get(url, allow_redirects=True)
open('hello.pdf', 'wb').write(myfile.content)

分塊下載大文件

import requests

url = 'https://www.cs.uky.edu/~keen/115/Haltermanpythonbook.pdf'
r = requests.get(url, stream = True)
with open("PythonBook.pdf", "wb") as Pypdf:
    for chunk in r.iter_content(chunk_size = 1024):
        if chunk:
            Pypdf.write(chunk)

參考資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章