urllib2 のソースを見ると、HTTPRedirectHandler をサブクラス化し、build_opener を使用してデフォルトの HTTPRedirectHandler をオーバーライドするのが最も簡単な方法のように見えますが、これは、本来あるべきことを行うために多くの (比較的複雑な) 作業のように思えます。ものすごく単純。
89675 次
7 に答える
233
リクエストの方法は次のとおりです。
import requests
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code, r.headers['Location'])
于 2013-02-03T22:42:27.047 に答える
37
Dive Into Pythonには、urllib2を使用したリダイレクトの処理に関する優れた章があります。別の解決策はhttplibです。
>>> import httplib
>>> conn = httplib.HTTPConnection("www.bogosoft.com")
>>> conn.request("GET", "")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
301 Moved Permanently
>>> print r1.getheader('Location')
http://www.bogosoft.com/new/location
于 2008-09-21T08:33:12.700 に答える
12
これは、リダイレクトに従わない urllib2 ハンドラです。
class NoRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
infourl = urllib.addinfourl(fp, headers, req.get_full_url())
infourl.status = code
infourl.code = code
return infourl
http_error_300 = http_error_302
http_error_301 = http_error_302
http_error_303 = http_error_302
http_error_307 = http_error_302
opener = urllib2.build_opener(NoRedirectHandler())
urllib2.install_opener(opener)
于 2011-03-18T13:33:06.233 に答える
9
requestメソッドのredirections
キーワードはhttplib2
赤いニシンです。最初のリクエストを返すのではなくRedirectLimit
、リダイレクトステータスコードを受け取った場合に例外が発生します。最初の応答を返すには、オブジェクトに設定follow_redirects
する必要があります。False
Http
import httplib2
h = httplib2.Http()
h.follow_redirects = False
(response, body) = h.request("http://example.com")
于 2012-05-14T16:45:38.060 に答える
8
これが役立つと思います
from httplib2 import Http
def get_html(uri,num_redirections=0): # put it as 0 for not to follow redirects
conn = Http()
return conn.request(uri,redirections=num_redirections)
于 2008-09-21T13:51:30.080 に答える
5
ただし、最短の方法は
class NoRedirect(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, hdrs, newurl):
pass
noredir_opener = urllib2.build_opener(NoRedirect())
于 2012-02-29T05:26:46.340 に答える
5
2番目のoltのPythonへのダイブへのポインタ。これがurllib2リダイレクトハンドラーを使用した実装です。本来よりも多くの作業が必要ですか?たぶん、肩をすくめる。
import sys
import urllib2
class RedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_301(
self, req, fp, code, msg, headers)
result.status = code
raise Exception("Permanent Redirect: %s" % 301)
def http_error_302(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_302(
self, req, fp, code, msg, headers)
result.status = code
raise Exception("Temporary Redirect: %s" % 302)
def main(script_name, url):
opener = urllib2.build_opener(RedirectHandler)
urllib2.install_opener(opener)
print urllib2.urlopen(url).read()
if __name__ == "__main__":
main(*sys.argv)
于 2008-09-21T11:31:20.713 に答える