python simulates logging in and keeps the cookie method detailed

  • 2020-05-27 06:23:26
  • OfStack


Recently, after crawling the data of, I have seen that you need to simulate login to get cookie before accessing the data you want to capture. The important thing is that the field authenticity_token in form of the login page of will be automatically generated every time you visit the login page, and it will be sent to the server by POST like your user name and password.

After one study, it was found that when you directly visit the website login interface, the response header of the server will have an Set-Cookie field, as follows:

%3D--a6ccd9a12a8af5c8b5fb6625c24bb4db0398c503; path=/; HttpOnly

In addition, the form of page form has an input of authenticity_token, which reads as follows:

<input type="hidden" name="authenticity_token" value="cGdhqVxDMRndpKbpvIV66wfEQlGf4Rz6UtXqsf79brEvFveHw2rCc6uz3euFEyUlpuA0azt5uNhnmrUiCaAyUg==" />

Previously, the value of _nosec_session was analyzed according to the logic of the back end. After decryption and various xx methods, the value of authenticity_token was obtained. Then, the value of username and password post were taken along with it. Always think with the back end of the problem, have to walk recently are not walking well. So just grab the generated authenticity_token value in the page and go with POST.

Using the requests library Session() The method is really easy to use, much more convenient than taking cookielib directly in the early days.


The login method of class XXX is used to simulate login, so just post the code for that part of the login.

class XXX:
 def login(self):

  r = self.s.get('')
  html = r.text
  p1 = re.compile(r'city_token" value="(.*?)"')
  res =,html)
  authenticity_token = str(
  print 'authenticity_token:',authenticity_token
  # print 'cookies',self.s.cookies
  # print s.cookies
  data = {
  r ='',data=data)
  # print r.headers
  # print r.request.headers
  # print self.s.cookies
  print '[*] OK!'
  return True

Call the login method and use it next time self.s.get() The request page will bring cookie with it.

I was once cheated by the train of thought and once by a slip of the pen (https was written as http), which made me crazy for a long time before I found this "BUG" = =, so I have to thank the code to improve the efficiency of Bug 2333!


Related articles: