programing

파이썬으로 URL을 요청하고 리디렉션을 따르지 않는 쉬운 방법이 있습니까?

elecom 2023. 7. 17. 20:40
반응형

파이썬으로 URL을 요청하고 리디렉션을 따르지 않는 쉬운 방법이 있습니까?

urllib2의 소스를 보면 HTTP DirectHandler를 하위 클래스로 분류한 다음 build_opener를 사용하여 기본 HTTP DirectHandler를 재정의하는 것이 가장 쉬운 방법인 것 같습니다. 하지만 이것은 매우 간단해야 할 것처럼 보이는 것을 하기 위해 많은 (상대적으로 복잡한) 작업인 것 같습니다.

요청 방법은 다음과 같습니다.

import requests
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code, r.headers['Location'])

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

redirections의 키워드httplib2요청 방법은 적청어입니다.첫 번째 요청을 반환하는 대신에 다음을 제기할 것입니다.RedirectLimit리디렉션 상태 코드를 수신하는 경우 예외입니다.설정해야 하는 초기 응답을 반환하려면follow_redirects로.False에서Http객체:

import httplib2
h = httplib2.Http()
h.follow_redirects = False
(response, body) = h.request("http://example.com")

이것이 도움이 될 것이라고 생각합니다.

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)

나는 파이썬으로 다이빙하기 위해 두 번째 오래된 포인터입니다.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())

언급URL : https://stackoverflow.com/questions/110498/is-there-an-easy-way-to-request-a-url-in-python-and-not-follow-redirects

반응형