简体   繁体   English

如何通过urlopen处理400错误请求?

[英]How to handle 400 Bad request by urlopen?

I use this piece of code to generate various statistics: 我使用这段代码来生成各种统计信息:

uClient = urlopen(finalURL)
page = uClient.read()
uClient.close()
obj = json.loads(page)
return obj

I have a list of everything that needs to be generated, but some of those URL do not exist anymore, but the file is too big to go thourgh it by hand. 我列出了需要生成的所有内容,但是其中一些URL不再存在,但是文件太大,无法手工处理。 Once it returns Bad request, the script runs into error, but I would like it to just pass that URL if it is a bad request and continue without existing. 一旦返回错误请求,该脚本就会出错,但是我希望它仅在该请求失败时才传递该URL,然后继续不存在该URL。

Try to use exception handling 尝试使用异常处理

try:
    uClient = urlopen(finalURL)
    page = uClient.read()
    uClient.close()
    obj = json.loads(page)
    return obj
except urllib2.HTTPError as e:
    if e.code == 404:
        print "Not found"

I tried this exception handling by @mkHun: 我尝试通过@mkHun处理此异常:

try:
   uClient = urlopen(finalURL)
   page = uClient.read()
   uClient.close()
   obj = json.loads(page)
   return obj
except ValueError:
  print "Not found"

but instead of using ValueError, I used urllib2.HTTPError as suggested by @tmadam which ultimately solved my problem. 但是我没有使用ValueError,而是使用了@tmadam建议的urllib2.HTTPError,最终解决了我的问题。 Thank you everyone! 谢谢大家!

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

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