Nad*_*mli 173

getcode()方法(在python2.6中添加)返回随响应一起发送的HTTP状态代码,如果URL不是HTTP URL,则返回None.

>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在Python 2.6中添加了getcode(). (14认同)
  • 在python 3.4中,如果有404,`urllib.request.urlopen`返回一个`urllib.error.HTTPError`. (3认同)

Joe*_*way 86

您也可以使用urllib2:

import urllib2

req = urllib2.Request('http://www.python.org/fish.html')
try:
    resp = urllib2.urlopen(req)
except urllib2.HTTPError as e:
    if e.code == 404:
        # do something...
    else:
        # ...
except urllib2.URLError as e:
    # Not an HTTP-specific error (e.g. connection refused)
    # ...
else:
    # 200
    body = resp.read()
Run Code Online (Sandbox Code Playgroud)

请注意,它HTTPErrorURLError存储HTTP状态代码的子类.


Xav*_*CLL 30

对于Python 3:

import urllib.request, urllib.error

url = 'http://www.google.com/asdfsf'
try:
    conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
    # Return code error (e.g. 404, 501, ...)
    # ...
    print('HTTPError: {}'.format(e.code))
except urllib.error.URLError as e:
    # Not an HTTP-specific error (e.g. connection refused)
    # ...
    print('URLError: {}'.format(e.reason))
else:
    # 200
    # ...
    print('good')
Run Code Online (Sandbox Code Playgroud)

  • 如何检查 301 或 302? (6认同)

小智 6

import urllib2

try:
    fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
    data = fileHandle.read()
    fileHandle.close()
except urllib2.URLError, e:
    print 'you got an error with the code', e
Run Code Online (Sandbox Code Playgroud)

  • TIMEX有兴趣获取http请求代码(200,404,500等),而不是urllib2抛出的一般错误. (5认同)