且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

URL存在时,urllib2捕获404错误

更新时间:2023-09-01 11:20:52

如果您想要获取正文,只需阅读 err.read():

If you want to get the body anyway, simply read the error response with an err.read():

import urllib2
uri = 'https://i.ytimg.com/vi/8Sii8G5CNvY/hqdefault.jpg?custom=true&w=196&h=110&stc=true&jpg444=true&jpgq=90&sp=68&sigh=OIIIAPOKNtx1OiZbAqdORlzl92g'
try:
  req = urllib2.Request(uri, headers={ 'User-Agent': 'Mozilla/5.0' })
  file = urllib2.urlopen(req)
except urllib2.HTTPError as err:
  if err.code == 404:
    print "Not Found"
    print err.read()