我如何使用 urllib.request.urlretrieve 和 python 2.7

How can I use urllib.request.urlretrieve with python 2.7

我正在尝试从 image-net.org 下载图像,以便创建 haar 级联分类器。我正在关注本教程 https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=18 但我使用的是 python 2.7 而不是 python 3。因此在教程中他有以下行:

urllib.request.urlretrieve(img, pathToImage)

而不是 import urllib.request 我这样做了 import urllib2 所以我尝试了这个但是它不是 vaild

urllib2.urlretrieve(i, "Negatives/"+str(num)+".jpg")

提前致谢!

您只需要导入不带“2”的 urllib

import urllib
urllib.urlretrieve(i, "Negatives/"+str(num)+".jpg")

在此Python urllib urlretrieve behind proxy

import urllib2

download = opener.urlretrieve(URL, "Negatives/"+str(num)+".jpg")

代码可以转化为

import urllib2

with open("Negatives/"+str(num)+".jpg",'wb') as f:
    f.write(urllib2.urlopen(URL).read())

我发现在不同的构建系统上,我会有不同版本的 Python 可用,完全不受我的控制。

所以我调整了我的脚本以这样获得urlretrieve

import sys
print("Python: " + sys.version)
sys.stdout.flush()

import os, re, difflib

# because somewhere along the line they  may have deprecated `urlretrieve`
#   mentioned in docs for python [3.5.5, 3.6.6, 3.7.0, 3.8.0a0] that:
#       `[urlretrieve] might become deprecated at some point in the future.`
def UrlRetrieve(url, fname=None):
  if sys.version_info[0] <= 2:
    import urllib
    return urllib.urlretrieve(url, fname)
  elif sys.version_info[0] <= 3:
    import urllib.request
    return urllib.request.urlretrieve(url, fname)
  else:
    import shutil
    import tempfile
    import urllib.request
    with urllib.request.urlopen(url) as response:
      if fname is None:
        with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
          shutil.copyfileobj(response, tmp_file)
          return (tmp_file.name, response.info())
      else:
        with io.open(fname) as the_file:
          shutil.copyfileobj(response, the_file)
          return (fname, response.info())

那么,这样使用:

url = "http://...whatever.../bootstrap.zip"
pair = UrlRetrieve(url)

然后,因为我导入的肯定是 python 2,所以我需要在 3 世界中这样做:

if sys.version_info[0] >= 3:
  import zipfile
  zip_ref = zipfile.ZipFile(pair[0], 'r')
  zip_ref.extractall(pair[0] + ".d")
  zip_ref.close()
  import os
  os.system("2to3 -w " + pair[0] + ".d")
  sys.path.append(pair[0] + ".d")
else:
  sys.path.append(pair[0])
from bootstrap_common import *

我现在保留这些片段句柄以供将来需要在 Python 2 和 3 上使用 urlretrieve 的脚本使用。