使用python下载图像文件

时间:2016-10-11 03:38:13

标签: python-2.7

我正在尝试从以下网页下载图片文件:

urls = 
['https://s3-media1.fl.yelpcdn.com/bphoto/VLu8pOKuwWz6rgeEDzAW1w/o.jpg'
'https://s3-media4.fl.yelpcdn.com/bphoto/-s4vJyj65E5q88MjpnIMSA/o.jpg'
'https://s3-media4.fl.yelpcdn.com/bphoto/cVk72YkYxrF17myMHAp1dQ/o.jpg']

这是我的代码:

import urllib

for i in urls:
     urllib.urlretrieve(i, ???.jpg)

每个网址都有一个图片文件,因此我想将文件保存如下:

VLu8pOKuwWz6rgeEDzAW1w.jpg
-s4vJyj65E5q88MjpnIMSA.jpg
cVk72YkYxrF17myMHAp1dQ.jpg

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您想要的文件名在网址中,因此请split()

使用它
urls =['https://s3-media1.fl.yelpcdn.com/bphoto/VLu8pOKuwWz6rgeEDzAW1w/o.jpg','https://s3-media4.fl.yelpcdn.com/bphoto/-s4vJyj65E5q88MjpnIMSA/o.jpg','https://s3-media4.fl.yelpcdn.com/bphoto/cVk72YkYxrF17myMHAp1dQ/o.jpg']
import urllib
for i in urls:
    j=i.split('/')[-2] # Splitting by '/' and assigning it to the name
    urllib.urlretrieve(i,'{}.jpg'.format(j))

Check this link