URL存在时,urllib2捕获404错误 [英] urllib2 catches 404 error while URL exists

查看:123
本文介绍了URL存在时,urllib2捕获404错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的错误:urllib2捕获404错误,同时打开一个有效的URL。我在浏览器中尝试了它,可以打开网址。我也传递了用户代理。

I faced with strange bug: urllib2 catches 404 error, while openning a valid url. I tryed it in browser, the url can be opened. Also I pass user-agent.

import urllib.request as 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:
    return "Not Found"

为什么我收到此错误?感谢您的回答。

Why I get this error? Thank you for answers.

推荐答案

如果您想要获取正文,只需阅读<$ c $的错误回复c> 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()

这篇关于URL存在时,urllib2捕获404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆