2017-09-03 26 views
0

我有一些图片的URL列表,我想下载它们 进口的urllibPython2.7如何循环的urllib下载图像

links = ['http://www.takamine.com/templates/default/images/gclassical.png', 
'https://dk1xgl0d43mu1.cloudfront.net/user_files/esp/product_images/000/010/120/large.png?1389980652', 
'https://dk1xgl0d43mu1.cloudfront.net/user_files/esp/product_images/000/020/676/large.png?1453396324'] 

#urllib.urlretrieve('http://www.takamine.com/templates/default/images/gclassical.png','image.jpg') 
for i in range(0,4): 
    S1 = 'image' 
    S2 = '.png' 
    name = list() 
    x = S1 + str(i) + S2 
    name.append(x) 

for q in links: 
    urllib.urlretrieve(q,name) 

我明白了如何检索一次一个...... 。当我尝试此代码,我得到这个错误

Traceback (most recent call last): File "C:/Python27/metal memes/test1.py", line 17, in urllib.urlretrieve(q,name) File "C:\Python27\lib\urllib.py", line 98, in urlretrieve return opener.retrieve(url, filename, reporthook, data) File "C:\Python27\lib\urllib.py", line 249, in retrieve tfp = open(filename, 'wb') TypeError: coercing to Unicode: need string or buffer, list found

任何答案,解释赞赏

回答

1

第一for循环是有创建的文件名列表image0.png到image3.png,对不对?这会失败并产生一个只包含一个元素('image3.png')的列表,因为您在循环内重新初始化列表。你必须在循环之前初始化一次。如果你把一个print name循环

第二个问题是后,您可以轻松地检查这个,你传递一个列表urllib.urlretrieve 你的问题并不清楚在这方面,但是你要下载一个名为image0 4个图像。 png ...来自每个给定网址的image3.png?这就是你的代码的样子。

如果是,则需要对文件名列表中的名称进行嵌套循环。我相应地修改了下面的代码。 但是你的网址已经包含了一个文件名,所以我不确定真正的内涵是什么。

links = ['http://www.takamine.com/templates/default/images/gclassical.png', 
'https://dk1xgl0d43mu1.cloudfront.net/user_files/esp/product_images/000/010/120/large.png?1389980652', 
'https://dk1xgl0d43mu1.cloudfront.net/user_files/esp/product_images/000/020/676/large.png?1453396324'] 

#urllib.urlretrieve('http://www.takamine.com/templates/default/images/gclassical.png','image.jpg') 

# create a list of filenames 
# either this code: 
names = list() 
for i in range(0,4): 
    S1 = 'image' 
    S2 = '.png' 
    x = S1 + str(i) + S2 
    names.append(x) 

# or, as suggested in the comments, much shorter using list comprehension: 
names = ["image{}.png".format(x) for x in range(4)] 

for q in links: 
    for name in names: 
     urllib.urlretrieve(q,name) 
+2

顺便说一句,'名= [ “图像{}。PNG” .format(x)的有效范围内的X(4)]' –

+1

感谢@ cricket_007,列表解析是蟒 – jps

+0

的非常好的和强大的功能感谢你们两个......我明白我的错误,并找到一个工作代码.... –