Javascript - Cookie acquisition and storage application

   In the previous blog, I introduced how to use Selenium to build a cookie pool, automate login, obtain information, etc. So what is a cookie? What is its function? Here, a brief introduction is repeated.


   A cookie is a small text file that the browser stores on the user's computer. The encrypted user information, expiration time, etc. are stored in this file, and a cookie will be brought with each request. When the user visits next time, the local cookie file and the url will be sent to the server together, and the server will use this to judge the user's status. Due to the limited capacity of the cookie, only 4kb, sometimes it is impossible to store all user information in it, so the session can solve this problem. The server queries other information of the user in the session through the identity information, so that all our operations will be preserved. . The following is an example to demonstrate how to set up a session.



insert image description here



import requests

session = requests.Session()
headers = {
    
    
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}

// 设置 session 的全局 headers
session.headers.update(headers)

// 默认使用全局的 headers
session.get('https://passport.vip.com/')

//自定义 headers
custom_headers = {
    
     'referer': 'https://passport.vip.com/' }


// 既有全局的 user-agent 也有自定义的 referer
session.get('https://passport.vip.com/', headers=custom_headers)


   Before explaining the acquisition and storage of cookies, briefly introduce the basic structure of cookies in the browser.



   It can be seen that the main components are the Name-Value key-value pair and the life cycle of Expires, that is, the expiration time.



insert image description here



   Obtain cookie: After creating and reading through the Document object document.cookie, split it into an array with a semicolon, and then add a judgment condition through a for loop. When the corresponding name is found, the corresponding user name is returned. Returns null if not found.



function getCookie(cname) {
    
    
  var name = cname + '=';
  var ca = document.cookie.split(';'); 
  for (var i = 0; i < ca.length; i++) {
    
    
      if (ca[i].indexOf(name) >= 0) {
    
    
         return ca[i].split('=')[1];
          }
        }
        return '';
  }


   Save and set cookie: Create a standard Chinese time object, and then set the life cycle of the cookie through the setTime() method, where getTime() is to convert the time object into a Greenwich time stamp (in milliseconds), and finally put The timestamp is converted to GMT standard time through the toGMTString() method.



function setCookie(cname, cvalue, exdays) {
    
    
   var d = new Date();
   d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
   var expires = 'expires=' + d.toGMTString();
   document.cookie = cname + '=' + cvalue + ';' + expires;
}


insert image description here



insert image description here



insert image description here



   Checking cookies: Add judgment conditions through the callback functions getCookie() and setCookie(). When a Local cookie is detected, a welcome prompt box will pop up automatically. Otherwise, you must enter the user name and save it in the cookie.

function checkCookie() {
    
    
   var user = getCookie('username');
   if (user) {
    
    
      alert('欢迎 ' + user + ' 再次访问');
        } else {
    
    
          user = prompt('请输入你的名字:');
          if (user) {
    
    
            setCookie('username', user, 8);
          }
        }
      }


   Finally, after the page is loaded through window.onload, the callback function checkCookie() is executed



    window.onload = function () {
    
    
       checkCookie();
      };


   The complete code is as follows:



<script>

 window.onload = function () {
    
    
        checkCookie();
      };

     
 function setCookie(cname, cvalue, exdays) {
    
    
    var d = new Date();
    d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    var expires = 'expires=' + d.toGMTString();
    document.cookie = cname + '=' + cvalue + ';' + expires;
      }

    
 function getCookie(cname) {
    
    
    var name = cname + '=';
    var ca = document.cookie.split(';'); 
    for (var i = 0; i < ca.length; i++) {
    
    
       if (ca[i].indexOf(name) >= 0) {
    
    
          return ca[i].split('=')[1];
          }
        }
    return '';
      }

 function checkCookie() {
    
    
    var user = getCookie('username');
       if (user) {
    
    
         alert('欢迎 ' + user + ' 再次访问');
        } else {
    
    
          user = prompt('请输入你的名字:');
          if (user) {
    
    
            setCookie('username', user, 8);
          }
        }
      }
</script>


   Test demonstration: For example, when logging in to the interface for the first time, enter the user name



insert image description here



   It can be seen that the user name and Expires entered in the test just now are successfully added to cookies, and the effective life cycle of the user is 8 days, which is the third parameter in the function setCookie() just now.



insert image description here



   When you close the browser without deleting the cookie, and then reopen it, since the system detects that the local cookie has a corresponding user name, it will automatically execute the content of the alert() function in checkCookie(), that is, the popup window statement.


   The next issue will continue to introduce examples of various applications in software development and testing. If you don’t understand, welcome to chat privately!



insert image description here

Guess you like

Origin blog.csdn.net/weixin_48591974/article/details/130577414