代码之家  ›  专栏  ›  技术社区  ›  Vishal

图像链接下载适用于Python 3,但不适用于Python 2.7

  •  -1
  • Vishal  · 技术社区  · 7 年前

    http://vignette2.wikia.nocookie.net/matrix/images/d/df/Thematrixincode99.jpg/revision/latest?cb=20140425045724 '

    我无法在Python 2.7.13上使用以下任何方法下载它:

    # METHOD 1
    url = 'http://vignette2.wikia.nocookie.net/matrix/images/d/df/Thematrixincode99.jpg/revision/latest?cb=20140425045724'
    urllib.urlretrieve(url, "local-filename.jpg")
    

    # METHOD 2
    resp = urllib.urlopen(url)
    image_data = resp.read()
    f = open('/tmp/abc.jpg', 'wb')
    f.write(image_data);
    f.close();
    

    req = urllib2.Request(img_url, headers={"User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"})
    response = urllib2.urlopen(req, None,15)
    obj_file = open(output_file,'wb')
    data = response.read()
    obj_file.write(data)
    response.close();
    

    每种情况下的输出文件大小为3KB。
    如何找出下载图像失败的原因?有什么解决方案吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Rahul    7 年前

    请再试一次:

    import requests
    r = requests.get("http://vignette2.wikia.nocookie.net/matrix/images/d/df/Thematrixincode99.jpg/revision/latest?cb=20140425045724")
    
    with open("local-filename.jpg", 'wb') as f:
        f.write(r.content)