以百度为例
1.首先确定我们需要的参数即百度的cookies需要什么参数才能识别为已登录状态.
通过百度我们得知只要下图中的参数即可实现登录状态
实例
public class Test5 { public static void main(String[] args) { WebDriver driver = getChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.baidu.com/"); sleep(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Cookie cookie = null; try { // cookie = new Cookie("BDUSS", "~NTaxMfE6sfvzOwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAeR2BwHkdgN");//不增加cookies过期日期 cookie = new Cookie("BDUSS", "W8wbFo1RFd3fjBX5aa0ZmSU5MM0wYXdpQVY5bmN6dERFSldpflhrOXdxMjVnRVFBQUFBJCQAAAAAAAAAAAEAAAC9HkU30sXN~NTaxMfE6sfvzOwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAeR2BwHkdgN", "www.baidu.com", "/", df.parse("2021-08-07"));//增加过期日期为2021-08-07 } catch (Exception e) { e.printStackTrace(); } driver.manage().addCookie(cookie);//添加cookies driver.navigate().refresh();//刷新看看是否登录 driver.get("https://www.baidu.com/"); sleep(); System.out.println(driver.manage().getCookieNamed("BDUSS"));//根据key获取value System.out.println(driver.manage().getCookies());//获取所有的cookies } private static void sleep() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
cookies的值来自于浏览器登录后F12 查看所得