Examples of code that uses URLLIB2 to prevent 302 jumps in Python

Source: Internet
Author: User
Description: Python's urllib2 Fetch Web page (urlopen) is automatically redirected (301,302). However, sometimes we need to get status information for 302,301 pages. You must obtain the debug information before turning.

The following code will be able to avoid 302 redirects to the new Web page

#!/usr/bin/python#-*-coding:utf-8-*-#encoding =utf-8#filename:states_code.py Import urllib2 class Redircthandler ( Urllib2. Httpredirecthandler): "" "  docstring for Redircthandler" ""  def http_error_301 (self, req, FP, code, MSG, headers) :    Pass def  http_error_302 (self, req, FP, code, MSG, headers):    pass def getunredirecturl (url,timeout=10):  req = urllib2. Request (URL)  Debug_handler = Urllib2. HttpHandler (debuglevel = 1)  opener = Urllib2.build_opener (Debug_handler, redircthandler)   html = None  Response = None  Try:    response = Opener.open (url,timeout=timeout)    html = response.read ()  except Urllib2. Urlerror as E:    if Hasattr (E, ' Code '):      error_info = E.code    elif hasattr (E, ' reason '):      error_info = E.reason  finally:    If response:      response.close ()  if HTML:    return HTML  else:    return Error_info HTML = getunredirecturl (' http://jb51.net ') print HTML
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.