Reprint--python Analog Login Code

Source: Internet
Author: User

Python version 3.5

#-*-coding:utf-8-*-Importre;ImportHttp.cookiejar;Importurllib.request, Urllib.parse, Urllib.errorImportOptparse;#------------------------------------------------------------------------------#check all cookies in cookiesdict are exist in Cookiejar or notdefcheckallcookiesexist (Cookienamelist, Cookiejar): Cookiesdict= {};  forEachcookienameinchCookienamelist:cookiesdict[eachcookiename]=False; Allcookiefound=True;  forCookiesinchCookiejar:if(Cookie.nameinchcookiesdict): Cookiesdict[cookie.name]=True;  forEachcookieinchCookiesdict.keys ():if( notCookiesdict[eachcookie]): Allcookiefound=False;  Break; returnAllcookiefound;#------------------------------------------------------------------------------#just for print delimiterdefprintdelimiter ():Print('-'*80)#------------------------------------------------------------------------------#main function to emulate login BaidudefEmulateloginbaidu ():Print("Function:used to demostrate the use of Python code to emulate login Baidu main page:http://www.baidu.com/")    Print("usage:emulate_login_baidu_python.py-u yourbaiduusername-p Yourbaidupassword") Printdelimiter (); #Parse Input ParametersParser =Optparse.    Optionparser (); Parser.add_option ("- u","--username", action="Store", type="string", default="', dest="username", help="Your Baidu Username"); Parser.add_option ("- P","--password", action="Store", type="string", default="', dest="Password", help="Your Baidu Password"); (options, args)=Parser.parse_args (); #Export all options variables, then later variables can be used     forIinchdir (options):exec(i +"= options."+i);    Printdelimiter (); Print("[preparation] using Cookiejar & Httpcookieprocessor to automatically handle cookies") CJ=Http.cookiejar.CookieJar (); Opener=Urllib.request.build_opener (Urllib.request.HTTPCookieProcessor (CJ));    Urllib.request.install_opener (opener);    Printdelimiter (); Print("[Step1] to get cookie Baiduid") Baidumainurl="http://www.baidu.com/"; Resp=Urllib.request.urlopen (Baidumainurl); #respinfo = Resp.info ();    #print "respinfo=", Respinfo;     forIndex, CookieinchEnumerate (CJ):Print('[', Index,']', Cookie) printdelimiter (); Print("[Step2] to get token value") Getapiurl="https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true"; Getapiresp=Urllib.request.urlopen (Getapiurl); #print "getapiresp=", Getapiresp;getapiresphtml = Getapiresp.read (). Decode ('Utf-8'); #print "getapiresphtml=", getapiresphtml;    #bdpass.api.params.login_token= ' 5ab690978812b0e7fbbe1bfc267b90b3 ';Foundtokenval = Re.search ("bdpass\.api\.params\.login_token= ' (? p<tokenval>\w+) ';", getapiresphtml); if(foundtokenval): Tokenval= Foundtokenval.group ("Tokenval"); Print("tokenval=", Tokenval) Printdelimiter (); Print("[STEP3] emulate login Baidu") Staticpage="http://www.baidu.com/cache/user/html/jump.html"; Baidumainloginurl="Https://passport.baidu.com/v2/api/?login"; Postdict= {            #' ppui_logintime ': "",            'CharSet':"Utf-8",            #' codestring ': "",            'token': Tokenval,#de3dbf1e8596642fa2ddf2921cd6257f            'Isphone':"false",            'Index':"0",            #' u ': "",            #' SAFEFLG ': "0",            'Staticpage': Staticpage,#http%3a%2f%2fwww.baidu.com%2fcache%2fuser%2fhtml%2fjump.html            'Logintype':"1",            'TPL':"mn",            'Callback':"Parent.bdpass.api.login._postcallback",            'username':"[email protected]",            'Password':"9279788280",            #' Verifycode ': "",            'Mem_pass':" on",        }; PostData= Urllib.parse.urlencode (postdict). Encode ("Utf-8"); #Here'll automatically encode values of parameters        #such as:        #encode http://www.baidu.com/cache/user/html/jump.html into http%3a%2f%2fwww.baidu.com%2fcache%2fuser%2fhtml% 2fjump.html        #print "Postdata=", PostData;req =urllib.request.Request (Baidumainloginurl, postdata); #In most case, the-do POST request, the Content-type, is application/x-www-form-urlencodedReq.add_header ('Content-type',"application/x-www-form-urlencoded"); Resp=Urllib.request.urlopen (req); #for index, cookies in Enumerate (CJ):        #print ' [', Index, '] ', cookie;Cookiestocheck = ['Bduss','PTOKEN','Stoken','Saveuserid']; Loginbaiduok=checkallcookiesexist (Cookiestocheck, CJ); if(Loginbaiduok):Print("+ + + emulate login Baidu is OK, ^_^")        Else:            Print("---Failed to emulate login Baidu!")    Else:        Print("Fail to extract token value from Html=", getapiresphtml)if __name__=="__main__": Emulateloginbaidu ();

Reprint--python Analog Login Code

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.