The URLLIB2 is a standard module that comes with Python and is used to send HTTP request. Similar to. NET, the HttpWebRequest class
Advantages of URLLIB2
The HTTP request sent by Python Urllib2 can be intercepted automatically by fiddler, which facilitates debugging.
Python can automatically process cookies
Disadvantages of URLLIB2
The header in the HTTP request sent by Python Urllib2 will be changed to "capitalize"
For example, your code is written in the header: Content-type=application/x-www-form-urlencoded, will be modified to content-type=application/ x-www-form-urlencoded
Instance one, get method, and custom header
#-*-Coding:utf-8-*-Importurllib2request= Urllib2. Request ("http://www.baidu.com/") Request.add_header ('Content-type','application/x-www-form-urlencoded') Response=Urllib2.urlopen (Request)PrintResponse.getcode ()PrintResponse.geturl ()PrintResponse.read ()
Example two, POST method
#-*-Coding:utf-8-*-ImportUrllib2Importurllibrequest= Urllib2. Request ("http://passport.cnblogs.com/login.aspx") Request.add_header ('Content-type','application/x-www-form-urlencoded') Data={"Tbusername":"Test_username","Tbpassword":"Test_password"}response=Urllib2.urlopen (Request, Urllib.urlencode (data))PrintResponse.getcode ()PrintResponse.geturl ()PrintResponse.read ()
Example three: processing of cookies
#-*-Coding:utf-8-*-ImportUrllib2ImportUrllibImportCOOKIELIBCJ=Cookielib. Cookiejar () opener=Urllib2.build_opener (urllib2. Httpcookieprocessor (CJ) Request= Urllib2. Request ("https://dynamic.12306.cn/otsweb/") Request.add_header ('Content-type','application/x-www-form-urlencoded') Data={"Tbusername":"Test_username","Tbpassword":"Test_password"}response=Opener.open (Request, Urllib.urlencode (data))#send again, you'll see cookies sent to Web serverResponse =Opener.open (Request, Urllib.urlencode (data))PrintResponse.getcode ()PrintResponse.geturl ()PrintResponse.read ()
Example four: How to handle jumps
When creating opener, Ul2. Httpredirecthandler is one of the handler that is added by default
Python automation Test (ix) URLLIB2 send HTTP Request