Pythonでは、どのように私はウェブサイトが404または200であるかどうかを確認するためにurllibは使用していますか?

StackOverflow https://stackoverflow.com/questions/1726402

質問

urllibは通過ヘッダのコードを取得するには?

役に立ちましたか?

解決

(のpython2.6で追加)

のgetcode()メソッドは、応答、またはURLがないHTTPのURLでない場合なしで送信されたHTTPステータスコードを返す。

>>> 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 (e.g. connection refused)
    # ...
else:
    # 200
    body = resp.read()

HTTPError には、その店舗URLErrorのサブクラスであることに注意してくださいHTTPステータスコードます。

は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')
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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top