简体   繁体   中英

How to avoid multiple try except blocks python

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

for ext in ('.png', '.jpg', '.gif', '.webm'):
    try:
        urllib.request.urlretrieve(imageLink + ext, str(threadName) + "/" + str(count) + ext)
        break
    except:
        pass

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM