在Python中,如何使用urllib查看网站是404还是200?

在Python中,如何使用urllib查看网站是404还是200?,python,urllib,http-status-codes,Python,Urllib,Http Status Codes,如何通过urllib获取头的代码?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.ge

如何通过urllib获取头的代码?

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
您还可以使用:

请注意,这是存储HTTP状态代码的
URLError
的子类。

对于Python 3:

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
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')

TIMEX感兴趣的是获取http请求代码(200、404、500等),而不是urllib2引发的一般错误。第二个
else
是错误吗?@NadavB异常对象“e”看起来像响应对象。也就是说,它类似于文件,您可以从中“读取”负载。要在python 3中使用,只需使用
from urllib.request import urlopen
。在python 3.4中,如果有404,
urllib.request.urlopen
返回
urllib.error。HTTPError
。在python 2.7中不起作用。如果HTTP返回400,则会出现异常,因为
print(e.reason)
可以使用。那么
HTTP.client.HTTPException
呢?如何检查301或302?
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')