如何在python 2.7中获取urllib2的状态代码

Tam*_*mpa 8 python

如何在python 2.7中获取urllib2的状态码?我不想使用请求.我需要urllib2.

    request = urllib2.Request(url, headers=headers)
    contents = urllib2.urlopen(request).read()
    print request.getcode()
    contents = json.loads(contents) 

     <type 'exceptions.AttributeError'>, AttributeError('getcode',), <traceback object at 0x7f6238792b48>
Run Code Online (Sandbox Code Playgroud)

谢谢

mdu*_*ant 10

退后一步:

result = urllib2.urlopen(request)
contents = result.read()
print result.getcode()
Run Code Online (Sandbox Code Playgroud)


Nis*_*ede 6

使用 getcode()

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

对于 urllib2

try:
    urllib2.urlopen('http://www.google.com/asdfsf')
except urllib2.HTTPError, e:
    print e.code
Run Code Online (Sandbox Code Playgroud)

将打印

404
Run Code Online (Sandbox Code Playgroud)