- 获取 cookie
driver.get_cookies()
- 添加 cookie
driver.add_cookie(cookie)
class TestCookieLogin:
def setup_class(self):
self.drvier = webdriver.Chrome()
def test_get_cookies(self):
# 1. 访问企业微信主页/登录页面
self.drvier.get("https://work.weixin.qq.com/wework_admin/frame#contacts")
# 2. 等待20s,人工扫码操作
time.sleep(20)
# 3. 等成功登陆之后,再去获取cookie信息
cookie = self.drvier.get_cookies()
# 4. 将cookie存入一个可持久存储的地方,文件
# 打开文件的时候添加写入权限
with open("cookie.yaml", "w") as f:
# 第一个参数是要写入的数据
yaml.safe_dump(cookie, f)
def test_add_cookie(self):
# 1. 访问企业微信主页面
self.drvier.get("https://work.weixin.qq.com/wework_admin/frame#contacts")
# 2. 定义cookie,cookie信息从已经写入的cookie文件中获取
cookie = yaml.safe_load(open("cookie.yaml"))
# 3. 植入cookie
for c in cookie:
self.drvier.add_cookie(c)
time.sleep(3)
# 4.再次访问企业微信页面,发现无需扫码自动登录,而且可以多次使用
self.drvier.get("https://work.weixin.qq.com/wework_admin/frame#contacts")
- 获取 cookie
driver.manage().getCookies();
- 添加 cookie
driver.manage().addCookie()
/**
* @Author: 霍格沃兹测试开发学社
* @Desc: '更多测试开发技术探讨,请访问:https://ceshiren.com/t/topic/15860'
*/
package com.ceshiren.hogwarts;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class CookieTest {
private static ChromeDriver driver;
private static WebDriverWait wait;
final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
@BeforeAll
public static void beforeAll() {
driver = new ChromeDriver();
driver.get("https://work.weixin.qq.com/wework_admin/frame");
wait = new WebDriverWait(driver, Duration.ofSeconds(1000));
}