简体   繁体   English

Python:使HTTP错误(500)不停止脚本

[英]Python: Make HTTP Errors (500) Not Stop Script

This is the basic part of my code that I need help with. 这是我代码中需要帮助的基本部分。 Note I learned python like last week. 注意我像上周一样学习了python。 I don't understand try and exceptions and I know that what I need for this, so if anyone could help that would be great. 我不懂尝试和例外,而且我知道我需要这样做,所以如果有人可以帮助,那就太好了。

url = 'http://google.com/{0}/{1}'.format(variable, variable1)
site = urllib.request.urlopen(url)

That's not the real website but you get the idea. 那不是真正的网站,但您可以理解。 Now I'm running a loop over 5 times per item, then running around 20 different items. 现在,我对每个项目运行5次以上的loop ,然后运行大约20个不同的项目。 So it goes to say google.com/spiders/ (runs 5 times with diff types of spiders) google.com/dogs/ (runs 5 times with diff types of dogs)etc. 因此可以说google.com/spiders/ (使用diff类型的蜘蛛运行5次) google.com/dogs/ (使用diff类型的狗运行5次)等。

Now the 2nd variable is the same on like 90% of the items I'm looping over, but 1 or 2 of them have some of the "types" but not others. 现在,第二个variable在我要遍历的90%的项目上都相同,但是其中1或2个具有某些“类型”,而没有其他。 So I get an http error 500 because that site doesn't exist. 所以我收到一个http error 500因为该站点不存在。 How do I make it basically skip that. 我如何使其基本上跳过这一点。 Its not something else, I know error 500 isn't the right error I believe, but I know the pages for those items don't exist. 它不是别的,我知道error 500不是我认为正确的错误,但是我知道这些项目的页面不存在。 So how do I set this up so that it just skips that one if it gets any error. 因此,我该如何设置它,使其在遇到任何错误时仅跳过该代码。

You can use a try/except block in your loop, like: 您可以在循环中使用try/except块,例如:

try:
    url = 'http://google.com/{0}/{1}'.format(variable, variable1)
    site = urllib.request.urlopen(url)
except Exception, ex:
    print "ERROR - " + str(ex)

You can also just catch specific exceptions - the above code would catch any exception (such as a bug in your code, not a network error) 您还可以捕获特定的异常-上面的代码将捕获任何异常(例如代码中的错误,而不是网络错误)

See here for more: https://wiki.python.org/moin/HandlingExceptions 看到这里更多: https : //wiki.python.org/moin/HandlingExceptions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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