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

时间:2017-07-19 10:44:01

标签: python python-2.7 urllib2 urllib

我有以下图片链接: 'http://vignette2.wikia.nocookie.net/matrix/images/d/df/Thematrixincode99.jpg/revision/latest?cb=20140425045724'

M无法在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 如何找出下载图像失败的原因?有什么决议吗?

更新:获得了可在Python 3上运行的更新。需要在Python 2.7上运行解决方案

1 个答案:

答案 0 :(得分:1)

再试一次:

    Map<String, List<String>> collect = Arrays.stream(value.split(","))
      .collect(Collectors.groupingBy(s -> s.split("  -  ")[0],
                          Collectors.mapping(s -> s.split("  -  ")[1],  Collectors.toList())));