By adding selenium-free cookie Login

【purpose】

By obtaining a browser cookie after a successful login, the interface is opened again by adding a free cookie data to achieve the effect of landing

A, selenium cookies by adding free landing

1, by selenium successful login, the login is successful, use driver.get_cookies () Gets Get all cookies

2, the data saved cookies

3, log on either interface, unknown to jump to the login screen

4, read cookies files get cookie, use driver.add_cookie () Add

5, refresh the interface, the interface displays the login status

Friendly reminder: cookie in httponly If the value is True, you can not log in this way

 

Reference Code:
 

#coding=utf-8
import json
from selenium import webdriver
import requests
class cookies:
    def __init__(self,driver):
        self.driver=driver

    #获取cookies保存到文件
    def save_cookie(self):
        cookies=self.driver.get_cookies()
        json_cookies=json.dumps(cookies)
        with open('d:/cookies_csnd.json','w') as f:
            f.write(json_cookies)
    #读取文件中的cookie
    def add_cookie(self):
        self.driver.delete_all_cookies()
        dict_cookies={}
        with open('d:/cookies.json','r',encoding='utf-8') as f:
            list_cookies=json.loads(f.read())
        for i in list_cookies:
            self.driver.add_cookie(i)
if __name__ == '__main__':
    driver=webdriver.Chrome()

    #进行登录

driver.find_element_by_xpath('//div/ul/li[@class="user"]/input').send_keys("xxxxxxxxxx")
driver.find_element_by_xpath('//div/ul/li[@class="password"]/input').send_keys("123456")
driver.find_element_by_xpath('//div/ul/li[@class="jump"]/button').click()   
cookies=cookies(driver)
cookies.save_cookie()#保存cookies
driver.delete_all_cookies()#删除当前所有的cookies
#打开想要跳转的界面,此步不可缺少,不然会报错
driver.get("xxxxxxxxx")
cookies.add_cookies()#添加cookie
driver.get("xxxxxxxxx")#重新打开,该界面显示登录状态

 

cookie contents Interpretation:

  • name: cookie name

  • value: cookie value corresponding to dynamically generated

  • domain: the domain name server

  • expiry: Cookie effective date of termination

  • path: Path attribute defines the page under which paths are available on the Web server Cookie server settings

  • httpOnly: Anti-scripting attack

  • secure: Mark the variables in the Cookie, show only when the communication protocol between the browser and the Web Server encryption authentication protocol

 

 

 

Guess you like

Origin blog.csdn.net/qq_35577990/article/details/89812933