如何处理urlopen的400个错误请求?

2024-06-30 15:05:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用这段代码生成各种统计数据:

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

我有一个需要生成的所有内容的列表,但是其中一些URL已经不存在了,但是文件太大了,无法手动处理。一旦它返回错误的请求,脚本就会出错,但是如果是错误的请求,我希望它只传递这个URL,然后在不存在的情况下继续。在


Tags: jsonobjurl内容closereadreturn错误
2条回答

我尝试了@mkHun的异常处理:

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

但是我没有使用ValueError,而是使用了@t.m.adam建议的urllib2.HTTPError,这最终解决了我的问题。谢谢大家!在

尝试使用异常处理

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"

相关问题 更多 >