0

I have some code that I wrote that downloads images from a website. The way that it currently works it needs to guess what the file extension will be for the url it will be downloading from. The block of code that does that looks like this:

for imageLink in imageLinks:


  try:
      urllib.request.urlretrieve(imageLink + ".png", str(threadName) + "/" + str(count) + ".png")
  except:
      try:
          urllib.request.urlretrieve(imageLink + ".jpg",str(threadName) + "/" + str(count) + ".png")
      except:
          try:
                urllib.request.urlretrieve(imageLink + ".gif",str(threadName) + "/" + str(count) + ".gif")
          except:
                urllib.request.urlretrieve(imageLink + ".webm",str(threadName) + "/" + str(count) + ".webm")

As it stands the code is relying on a fail in order to try something else. I wanted to know if their is a way to have this functionality but to basically just look better. These methods will give identical errors if they fail so I want to just go through them sequentially until one works

1
  • 1
    Wrap the request in a function that you pass your URL to as a parameter Commented Dec 19, 2018 at 17:42

2 Answers 2

6
for ext in ('.png', '.jpg', '.gif', '.webm'):
    try:
        urllib.request.urlretrieve(imageLink + ext, str(threadName) + "/" + str(count) + ext)
        break
    except:
        pass
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a try/except block inside a function and return None if the control goes to the except statement. You can optimize the for loop according to your own needs. One example is here:

def get_url(link1, link2):
try:
    requestData = urllib.request.urlretrieve(link1, link2)
except:
    return None
return requestData

for imageLink in imageLinks:
data = urllib.request.urlretrieve(imageLink + ".png", str(threadName) + "/" + str(count) + ".png")
if data == None:
    data = urllib.request.urlretrieve(imageLink + ".jpg",str(threadName) + "/" + str(count) + ".png")
    if data == None:
        data = urllib.request.urlretrieve(imageLink + ".gif",str(threadName) + "/" + str(count) + ".gif")
        if data == None:
            urllib.request.urlretrieve(imageLink + ".webm",str(threadName) + "/" + str(count) + ".webm")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.