0

HTTP 応答コードを取得するために次のレシピを使用していますが、3xx を取得できません。

import urllib2
for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
    try:
        connection = urllib2.urlopen(url)
        print connection.getcode()
        connection.close()
    except urllib2.HTTPError, e:
        print e.getcode()

urllib2 のリダイレクト処理を無効にするにはどうすればよいですか?

4

2 に答える 2

4

これは直接的な答えではありませんが、この場合、リクエストを使用する方がはるかに優れています

import requests
for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
    print requests.head(url).status_code
于 2013-01-31T12:52:04.987 に答える
4

各リダイレクト応答コードを任意の方法で処理するHTTPRedirectHandlerのサブタイプを作成できます。次に、urllib2.build_openerを使用してカスタム リダイレクト ハンドラをオープナーにビルドし、デフォルトのリダイレクト ハンドラをそのように上書きします。

于 2013-01-31T12:45:18.110 に答える