In your program, you have a try/ except block, but it does not surround the line: req=urllib.request.urlopen('XXXXXXXX'+line) You probably should modify the extent of the exception handling to include that part. If you are seeing a 504, I expect it to come at this point.