Mounarajan Mounarajan - 5 months ago 21
Python Question

While loop limit times

How to retry this fucntion only for three time when error occured

def crawl(url):
while True:
try:
data = os.popen('wget -qO- -T10 --tries=1 --header="Accept: text/html" --user-agent="User-Agent: Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 " %s'% url).read()
return data
except Exception, e:
print e
pass

crawl("http://aaa.com")


How to retry for three times inside the
while
loop?

Answer

you can add a counter to the loop condition.

c = 0
while c < 3:
  try:
    ..
  expect ...
    c = c + 1