Python simulate Baidu Login instance code

Source: Internet
Author: User

Originally write this gadget is intended to be used to automatically login Baidu, and then according to the ranking of the bottom of the crawl member head, such as the creation of a paste of thousands of people head picture or million person head picture. is also regarded as practicing practicing.
After the completion of the find to catch that bar post completely do not need to login ... Good, later used to do automatic one key sign in (often forget to clock out), rob the second floor of what, also nice ~ ~
Now on the blog to send an article on how long it is copied away, feel that they can do is only here to despise them.
Nonsense too much, easy to hate, the following is code:

#-*- coding:gbk -*-# #  analog Baidu login  for python2.7 #  which shows the verification code part   need to use PIL library #  need authentication code

, a tkinter window is created to display and enter the verification code, and the window closes when the carriage returns. # import urllib, urllib2, cookielib, re, time username   =  ' Yourusernamehere '   #用户名 password   =  ' yourpasswordhere '   #密码 cookiefile =  '--login-baidu--'    #cookie文件 #模拟header信息 headers = {          "Host": "passport.baidu.com",          "Referer": "http:// Www.baidu.com/cache/user/html/login-1.2.html ",         " user-agent ":" mozilla/5.0  (windows nt 6.1)  AppleWebKit/537.36  (Khtml, like gecko)   chrome/43.0.2357.124 safari/537.36 ",         " Origin ":" http:// Www.baidu.com ",         " "" Yufang xiao tou.   this code by zhengxiao (Www.zh30.om) ""           "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",           "Cache-control": "Max-age=0",          " Connection ":" Keep-alive "            } cookie =  Cookielib. Mozillacookiejar (Cookiefile) #尝试加载cookie文件并验证有效性 try:     cookie.load (ignore_discard=true,  ignore_expires=true)     print  ' cookie success ' read login status      #do  something      except exception:      #cookie不存在或无效时   Start a mock login and regenerate the cookie file     opener = urllib2.build_opener (urllib2. Httpcookieprocessor (cookie))     loginUrl =  ' http://www.baidu.com/cache/user/html
/login-1.2.html '    getTokenUrl =  ' Https://passport.baidu.com/v2/api/?getapi&class=login &tpl=mn&tangram=true '   ' "" www . zh30 . com  "" "     getcodestringurl =  ' Https://passport.baidu.com/v2/api/?logincheck&callback=bdPass.api.login._ Needcodestringcheckcallback&tpl=mn&charset=utf-8&index=0&username= '  + username  +  ' &isphone=false&time=1436429688644 '     loginPostUrl =  ' https:// Passport.baidu.com/v2/api/?login '      #获取BAIDUID, token     request  = urllib2. Request (Loginurl, headers=headers)     response = opener.open (Request)      request = urllib2.
Request (Gettokenurl, headers=headers)     response = opener.open (Request)     hastoken = response.read ()      token = re.search (R ' login_token\s*=\s*\ ' (. +?) \ ", Hastoken). Group (1)           #检查username是否需要验证码      request = urllib2. Request (getcodestringurl, headers=headers)     response = opener.open ( Request)     getcodestring = response.read ()     codestring  = re.search (R ' "codestring": "?
[^ "]+"] "?, ',  getcodestring. Group (1)     if codestring ==  ' null ' &NBSP:         codestring =  '          verifycode =  '     else:           #需要验证码   Create a TK display verification code   and prompt the user to enter         genimageurl =   ' Https://passport.baidu.com/cgi-bin/genimage? '  + codestring + ' &v= '  + str Long (time.time () *1000)         import  IO,&NBSP;TKINTER&NBSP;AS&NBSP;TK         from pil import &NBSP;IMAGE,&NBSP;IMAGETK         request = urllib2. Request (genimageurl, headers=headers)         image_bytes =  opener.open (Request). Read ()         pil_image =  Image.open (IO. Bytesio (image_bytes))         def presskey (event):              global verifycode      &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;IF&NBSP;EVENT.KEYCODE&NBSP;==&NBSP;13:                      verifycode  = entry.get ()                      tk_root.destroy ()         tk_root = tk. Tk ()         tk_image = imagetk.photoimage (pil_image)          label1 = tk. Label (tk_root, text= ' Your account exception, require input authentication code ')         label1.pack ()          label2 = tk. Label (Tk_root, image=tk_image)         label2.pack ()          label3 = tk. Label (tk_root, text= ' Enter verification code and press ENTER to confirm ')         label3.pack ()          entry = tk. Entry (tk_root)         entry.bind (' <Key> ',  presskeY)         entry.pack ()          Tk_root.mainloop ()      #构造登录表单     data = {              "Ppui_logintime": "134198",               "CharSet": "Utf-8",               "codestring": "",            
  "Isphone": "false",              "index": "0",              "U": "",               "SAFEFLG": "0",               "Staticpage": "http://www.baidu.com/",               "Logintype": "1",              "TPL": "MN",              "" "yufang xiao tou.   this code by zhengxiao "" "              "callback": "Parent.bdpass.api.login._postcallback",               "Mem_pass": "On" &NBSP;&NBSP;&NBSP;&NBSP;}     data[' token ']  = token     data[' username '] = username     data[' Password '] = password     data[' codestring '] = codestring      data[' Verifycode '] = verifycode      #开始登录     req  = urllib2. Request (Loginposturl, urllib.urlencode (data),  headers)     result =&nbspOpener.open (req). Read ()      #验证登录结果          errno  = re.search (R ' &error= (\d+) ',  result). Group (1)     if errno ==   ' 0 ':         print  ' login successful '          cookie.save (ignore_discard=true,ignore_expires=true)     elif errno  ==  ' 4 ':         print  ' Login failed: password error '      elif errno ==  ' 257 ':         print  '
Logon Failure: Authentication code error '     else:         print  ' Login failed '         print result  #失败后   Print return character  by zh30.com


When Baidu logs on, there are four main steps.
First step: Visit any Baidu page, get a cookie named Baiduid
Step Two: Request a token based on a cookie (to submit this value at login).
Step Three: Verify that the username requires a captcha. If there is a codestring in the return value, the authentication code is required and then the authentication code is obtained according to the codestring request.
Step Fourth: Submit the Login form, check the login status, and record cookies. To determine whether the login was successful, you can check whether a cookie named Bduss is generated, Zhengxiao here to return a jump link in the string, and the error parameter is 0 when successful.
have fun!

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.