Search code examples
pythonimagesaveurllib

How do I download images to the folder I specify with Python urllib request?


For example, I want to download the pictures to the folder named pictures. How can I do this with urllib request

import os
import urllib.request
try:
    klasor_yarat = os.mkdir("resimler")
except:
    pass
say = 1
for i in resim_listesi:
    urllib.request.urlretrieve(i,str(klasor_yarat)+"\"resim" +str(say)+ ".jpg")
    say+=1

Solution

  • There seem to be several problems here:

    • "\"resim" is not the correct way to put a '/' in the string. You have to use "/" or "\\".
    • str(klasor_yarat) returns "None".
    • You are adding a ".jpg" to the image retrieved. What if the image is a different extension?
    • Make sure resim_listesi is an iterable. I can't know that because it's not defined in the code given.
    • Lastly, try using English names for variables as that will improve the readability of your code for others.

    Anyway, this should probably work.

    import os
    import urllib.request
    try:
        klasor_yarat = os.mkdir("resimler")
    except:
        pass
    say = 1
    for i in resim_listesi:
        urllib.request.urlretrieve(i,"resimler/resim" +str(say)+ ".jpg")
        say+=1