129

urllib を介してヘッダーのコードを取得する方法は?

4

4 に答える 4

185

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
于 2009-11-13T00:45:14.387 に答える
89

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

は HTTP ステータス コードを格納HTTPErrorするサブクラスであることに注意してください。URLError

于 2009-11-13T00:46:01.280 に答える
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
于 2011-07-08T19:25:41.567 に答える