selenium如何操作cookies实现免登录

执行接口测试或者某些自动化测试时,为了避免每次访问接口都需要登录操作,可以用访问接口时,把cookies信息传过去。

思路是先登录一次页面,获取到cookies信息,把cookies信息保存到本地文件,以后再访问页面时直接拿本地的cookies文件传过去

package com.gmsd;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.StringTokenizer;
 
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
/**
 * @author QiaoJiaofei
 * @version 创建时间:2015年7月2日 上午10:29:54
 * 类说明
 */
public class TestCookie {
     
    WebDriver dr = null;
     
    public static void main(String args[]) {
         
        TestCookie t = new TestCookie();
        t.wtriteC();
        t.getC();
    }
    public void wtriteC() {
        System.setProperty("webdriver.chrome.driver", "D:/BaiduYunDownload/selenium/chromedriver.exe");
        dr = new ChromeDriver();
        dr.get("http://172.16.30.209:5555/login.shtml");
         
        dr.findElement(By.id("inputEmail")).sendKeys("18600363820");
        dr.findElement(By.id("inputPassword")).sendKeys("123456");
        dr.findElement(By.id("denglu")).click();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
         
        File file = new File("D:/JavaTestFile/TestCookies.txt");
                 
        Set<Cookie> s = dr.manage().getCookies();
         
         
        if(file.exists()) {
            file.delete();
            try {
                file.createNewFile();
 
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            for(Cookie c:s) {
                bw.write(c.getDomain()+";"+c.getName()+";"+c.getValue()+";"+c.getPath()+";"+c.getExpiry()+";"+c.isSecure());
                bw.newLine();
            }
            bw.flush();
            bw.close();
            fw.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        dr.quit();
    }
    public void getC() {   
        System.setProperty("webdriver.chrome.driver", "D:/BaiduYunDownload/selenium/chromedriver.exe");
        dr = new ChromeDriver();
        dr.get("http://172.16.30.209:5555");
        File file = new File("D:/JavaTestFile/TestCookies.txt");
        try {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String line = null;
            while((line=br.readLine())!=null) {
             
                 
                String [] sz = line.split(";");
                String doman =  sz[0].trim();
                String name = sz[1].trim();
                String value = sz[2].trim();
                String path = sz[3].trim();
                Date date = null;
 
                if(!(sz[4].equals("null"))){   
                    date = new Date(sz[4]);
                    //System.out.println("date="+date);
 
                }
                Boolean bl = Boolean.valueOf(sz[5]);
             
                 
                Cookie ck = new Cookie(name,value,doman,path,date,bl);
                dr.manage().addCookie(ck);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         
        dr.get("http://172.16.30.209:5555");
        //dr.quit();
    }
}
writerC()方法是获取cookies并存到本地文件,主要使用selenium的Set<Cookie> s = dr.manage().getCookies();
getC()方法是从本地文件读取cookies信息,主要使用

Cookie ck = new Cookie(name,value,doman,path,date,bl);
dr.manage().addCookie(ck);

注意几点:

1、Cookie的构造方法的参数是有顺序的

2、getC()调用了两次url,第一次是往url传cookies,第二次是为了刷新,也可使用dr.navigate().refresh();

 

 

其他参考:

https://www.cnblogs.com/qiaoyeye/p/4649328.html 
https://www.cnblogs.com/xiaoxiaolvdou/p/9297063.html
https://zhuanlan.zhihu.com/p/133636632?utm_source=wechat_session
https://blog.csdn.net/fabbychips/article/details/90177737
https://www.php.cn/python-tutorials-392248.html
https://blog.csdn.net/pzzhuzhu/article/details/108776759
https://blog.csdn.net/ab_2016/article/details/78427084
https://www.cnblogs.com/longronglang/p/9512229.html
https://www.pianshen.com/article/4464166364/

https://www.cnblogs.com/superhin/p/11481803.html
https://blog.csdn.net/ab_2016/article/details/78427084
https://blog.csdn.net/qq_28802477/article/details/62417780  **********

posted @ 2020-12-14 00:42  peachlf  阅读(415)  评论(0编辑  收藏  举报