一、查看浏览器cookie
cookie、session、token的区别:
- cookie存储在浏览器本地客户端,发送的请求携带cookie时可以实现登录操作。
- session存放在服务器。
- token应用于应用程序。
F12查看浏览器cookie:
二、cookie基本操作
1、获取cookie:
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()
运行结果如下:
2、删除单个cookie:
driver.delete_cookie('BAIDUID')
3、删除全部cookie:
driver.delete_all_cookies()
4、添加某个cookie:
driver.add_cookie({"name":"STORM","value":"123456"})
三、获取cookie并实现免登录
以登录163邮箱为例。
1、首先登录163邮箱,将cookie保存到本地文件中:
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('xxx@163.com')
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()
运行完成后,脚本所在目录会生成一个名为"mycookie.json"的文件,文件内容如下:
2、然后通过读取该cookie文件,实现免登录效果:
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()
注意:
- 在添加cookie时,需要将expiry对应的值转换为整型,否则会报错。
- 添加cookie后,需要借助refresh关键字刷新页面
- cookies存在有效期,之前导出的cookie可能会失效,失效则需要重新导出。
四、封装成函数
为方便后续调用“通过cookie实现免登录”的方法,可以将代码封装成函数:
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()