how to check if the urllib2 follow a redirect?

前端 未结 2 905
悲&欢浪女
悲&欢浪女 2020-12-19 10:00

I\'ve write this function:

def download_mp3(url,name):
        opener1 = urllib2.build_opener()
        page1 = opener1.open(url)
        mp3 = page1.read()
         


        
相关标签:
2条回答
  • 2020-12-19 10:32

    Something like this, and check code:

    import urllib2, urllib
    
    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)
    response = urllib2.urlopen('http://google.com')
    if response.code in (300, 301, 302, 303, 307):
        print('redirect')
    
    0 讨论(0)
  • 2020-12-19 10:33

    My answer to this looked like

    req = urllib2.Request(url)
    try:
       response = urllib2.urlopen(url)
    except urllib2.HTTPError as e:
       # Do something about it
       raise HoustonWeHaveAProblem
    else:
       if response.url != url:
           print 'We have redirected!'
    
    0 讨论(0)
提交回复
热议问题