あかかわらず、全ての要求URL pythonには従わず、リダイレクト?
質問
みの源泉urllib2うための最も簡単な方法はないサブクラスHTTPRedirectHandlerおよびその利用build_openerをオーバーライドのデフォルトHTTPRedirectHandler、このように多くの(比較的複雑な作業が何を感じられるようにすべきか。
解決
こちらは ご要望 方法:
import requests
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code, r.headers['Location'])
他のヒント
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
この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)
と思うこと
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)
の redirections
キーワード httplib2
請求方法は赤ニシン.帰るのではなく、最初の要請を調達する RedirectLimit
る場合の例外でのリダイレクト状態コードです。のinital応答を設定する必要がありま follow_redirects
へ False
の Http
オブジェクト:
import httplib2
h = httplib2.Http()
h.follow_redirects = False
(response, body) = h.request("http://example.com")
ったoltのポインタ Dive into 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)
そし
class NoRedirect(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, hdrs, newurl):
pass
noredir_opener = urllib2.build_opener(NoRedirect())
所属していません StackOverflow