簡體   English   中英

使用什么命令代替 urllib.request.urlretrieve?

[英]What command to use instead of urllib.request.urlretrieve?

我目前正在編寫一個腳本,用於從 URL 下載文件

import urllib.request
urllib.request.urlretrieve(my_url, 'my_filename')

文檔urllib.request.urlretrieve state:

以下函數和類是從 Python 2 模塊 urllib(相對於 urllib2)移植而來的。 它們可能會在將來的某個時候被棄用。

因此我想避免它,這樣我就不必在不久的將來重寫這段代碼。

我無法在標准庫中找到另一個接口,如download(url, filename) 如果urlretrieve被認為是 Python 中的遺留接口 3,替換的是什么?

requests 非常適合這個。 雖然安裝它有一些依賴項。 這是一個例子。

import requests
r = requests.get('imgurl')
with open('pic.jpg','wb') as f:
  f.write(r.content)

已棄用是一回事,將來可能會被棄用是另一回事。

如果它適合您的需求,我會繼續使用urlretrieve

也就是說,你可以不用它:

from urllib.request import urlopen
from shutil import copyfileobj

with urlopen(my_url) as in_stream, open('my_filename', 'wb') as out_file:
    copyfileobj(in_stream, out_file)

另一種不使用shutil且沒有其他外部庫(如requests解決方案。

import urllib.request

image_url = "https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png"
response = urllib.request.urlopen(image_url)
image = response.read()

with open("image.png", "wb") as file:
    file.write(image)

不確定這是否是您正在尋找的,或者是否有“更好”的方法,但這是我在庫之后添加到腳本頂部的內容,以使我的腳本與 Python 2/3 兼容。

# Python version compatibility
if version.major == 3:
    from urllib.error import HTTPError
    from urllib.request import urlopen, urlretrieve

elif version.major == 2:
    from urllib2 import HTTPError, urlopen

    def urlretrieve(url, data):
        url_data = urlopen(url)
        with open(data, "wb") as local_file:
            local_file.write(url_data.read())
else:
    raise ValueError('No valid Python interpreter found.')

這至少看起來像是一個方便的技巧,我希望這可能對某人有所幫助。

最好!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM