在Python中,如何使用urllib来查看网站是404还是200?
如何通过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
你也可以使用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 (eg connection refused) # ... else: # 200 body = resp.read()
请注意, HTTPError
是存储HTTP状态码的URLError
的子类。
对于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 (eg 404, 501, ...) # ... print(e.code) except urllib.error.URLError as e: # Not an HTTP-specific error (eg connection refused) # ... print('URLError') else: # 200 # ... print('good')
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