python - try url, if error, then try next url. How? -


I am new to Python I have been searched through SO and Google, and I can not understand it.

I have a script that attempts to connect to an API. However, when it returns an error, then I want to try the next URL for that API.

Even what I have so far:

  def fun1 (): try: raw = urllib2.urlopen (pubapi1) .read () dictionary = Json.loads (raw) URLError, except error: print error  

I'm not sure where to go after this. If it fails, then I want to check it out pupapi2, pupapi3, etc.

Once it successfully connects to a URL, then I want to continue the program.

Is there any advice?

. . Update:

OK, so I have given you advice, Deepawali, and now I have this:

  raw = 0 def Func (): Try: #Rotate Public API URL = [pubapi1, pubapi2, pubapi3] URL: via url: Try: Global Raw Raw = urllib2.urlopen (url) .read URLError, except error ( ) Print "Success" Return: Print str (error) + ": Attempt to connect to the next public API" time.sleep (1) Other: Print "Public API Can not connect to, try again later # # API rotation  

spit it out:

HTTP error 502: Bad gateway : The next folk api

success

and the attempt to connect again breaks the program I know that it is not connected, and it should not be because the API Still down. However, I believe that it still shows that it still has two other HTTP APIs Try to connect Rel to "HTTP Error 502: Bad Gateway: Try the following to connect to a public API should" print twice. In addition, it should not print "success", unless it is actually linked to an active API URL.

Any suggestions?

You want to wrap your try / leaving a loop flow control and through all those URLs Iterate what you care about.

Abstract Example

  # / usr / bin / Python def function (): for a_list = ["foo", "bar", "baz"] A_list: try: if i == "foo": To throw an exception to #fu, false print "Hey!% S will be stressed on work!" % I Return # We should not see Falcon print except: Print "% s error"% i func () & gt; & Gt; Foo error'd & gt; & Gt; Oh times worked  

Optimized for your update code.

  #! / Usr / bin / python import urllib2 import urllib2 import urlibr import time def func (): # rotate via the URL of the public API = ['http: //www.google.comx', # fail 'http: // www .google.comd ', # fail' http: //Www.google.comc ', # fail' http://www.google.com ', #Support' http: //www.google.chaoij '] # url Try: url_urlopen (URL) .read () print URLError, "breakthrough", except error, return: print str (error) + ': try: global raw # (? Global) Trying to connect to the next public API "time.sleep (1) # You really do not Nd should carry out Func ()  


Comments

Popular posts from this blog

winforms - C# Form - Property Change -

javascript - amcharts makechart not working -

java - Algorithm negotiation fail SSH in Jenkins -