[Python] Selenium operates cookies to achieve login-free

1. View browser cookies

The difference between cookie, session and token:

  • The cookie is stored in the local client of the browser, and the login operation can be realized when the request sent carries the cookie.
  • The session is stored on the server.
  • Tokens are used in applications.

F12 to view browser cookies:
insert image description here

2. Basic operation of cookies

1. Get cookies:

from selenium import webdriver

url = "http://www.baidu.com/"
driver = webdriver.Chrome()
driver.implicitly_wait(20)
driver.get(url)
cur_cookies = driver.get_cookies() #获取所有cookie
baidu_id_cookie = driver.get_cookie('BAIDUID')  #获取单个cookie
print(len(cur_cookies))
print(cur_cookies) #输出cookie值
print(baidu_id_cookie)
driver.quit()

The result of the operation is as follows:
insert image description here

2. Delete a single cookie:
driver.delete_cookie('BAIDUID')
3. Delete all cookies:
driver.delete_all_cookies()
4. Add a cookie:
driver.add_cookie({"name":"STORM","value":"123456"})

3. Obtain cookie and realize login-free

Take logging in to 163 mailbox as an example.
1. First log in to the 163 mailbox and save the cookie to a local file:

from selenium import webdriver
from time import sleep
import json
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://mail.163.com/')
driver.implicitly_wait(20)
driver.switch_to.frame(0)
driver.find_element(By.NAME,"email").send_keys('[email protected]')
driver.find_element(By.NAME,"password").send_keys('xxxxxx')
driver.find_element(By.ID,"dologin").click()
sleep(3)
mycookies = driver.get_cookies()
jsoncookies = json.dumps(mycookies)
with open("mycookie.json",'w') as f:
    f.write(jsoncookies)
driver.quit()

After the operation is completed, a file named "mycookie.json" will be generated in the directory where the script is located. The content of the file is as follows:
insert image description here
2. Then, by reading the cookie file, the login-free effect is realized:

from selenium import webdriver
import time
import json
from time import sleep

driver = webdriver.Chrome()
driver.get("https://mail.163.com")
cookie_file_path = "mycookie.json"
with open(cookie_file_path,"r") as f:
    cookies_str = f.readline()
    cookies_dict = json.loads(cookies_str)

driver.delete_all_cookies() # 删除当前网址的所有cookie
for cookie in cookies_dict: # 循环读取cookie
    for k in cookie.keys(): # 判断一下
        if k == "expiry":
            cookie[k] = int(cookie[k]) # expiry参数必须为整型
        driver.add_cookie(cookie)
time.sleep(2)
driver.refresh()
sleep(5)
driver.quit()

Notice:

  • When adding a cookie, you need to convert the value corresponding to expiry to an integer, otherwise an error will be reported.
  • After adding the cookie, you need to refresh the page with the refresh keyword
  • Cookies have an expiration date. Previously exported cookies may become invalid. If they become invalid, they need to be re-exported.

Four, encapsulated into a function

In order to facilitate subsequent calls to the method of "realizing login-free through cookies", you can encapsulate the code into a function:

def url_with_cookie(driver, target_url, file):
    cookies_file_path = file
    cookies_file = open(cookies_file_path,"r")
    cookies_str = cookies_file.readline()
    cookies_dict = json.loads(cookies_str)
    time.sleep(2)
    driver.get(target_url)
    driver.delete_all_cookies()
    for cookie in cookies_dict:
        for k in cookie.keys():
            if k =="expiry":
                cookie[k] = int(cookie[k])
            driver.add_cookie(cookie)
    time.sleep(2)
    driver.refresh()

if __name__ == '__main__':
    from selenium import webdriver
    import json
    import time
    from time import sleep

    driver = webdriver.Chrome()
    url_with_cookie(driver,'https://mail.163.com','mycookie.json')
    sleep(5)
    driver.quit()

Guess you like

Origin blog.csdn.net/jylsrnzb/article/details/131599519