多测师是一家拥有先进的教学理念,强大的师资团队,业内好评甚多的接口自动化测试培训机构!

17727591462

联系电话

您现在所在位置:接口自动化测试培训 > 新闻资讯

Selenium2操作浏览器的Cookies-自动化测试

更新时间:2022-04-25 09:00:19 作者:多测师 浏览:147

  一、cookies广泛应用于web技术中,它伴随用户请求在web服务器和浏览器之间传递.....本文就在selenium WebDriver中如何读取浏览器的cookies以及如何在浏览器中使用已有的cookies 这两个方面而展开。

Selenium2操作浏览器的Cookies-自动化测试

  二、首先,分析第一个问题:WebDriver中如何读取浏览器的cookies?WebDriver包中已封装好关于Cookies的相关类和方法,通过WebDriver的manage().getCookies()方法

  而获取,详见下面代码:

  File cookieFile = new File(COOKIE_PATH);

  try {

  if(cookieFile.exists()){

  cookieFile.delete();

  }

  cookieFile.createNewFile();

  System.out.println("Create a new cookie file in:"+System.getProperty("user.dir"));

  //将当前的cookies写入指定文件

  BufferedWriter bWriter = new BufferedWriter(new FileWriter(cookieFile));

  for(Cookie cookie : driver.manage().getCookies()){

  bWriter.write(

  cookie.getName() + "/"

  + cookie.getValue() + "/"

  + cookie.getPath() + "/"

  + cookie.getExpiry() + "/"

  + cookie.isSecure());

  bWriter.newLine();

  }

  bWriter.flush();

  bWriter.close();

  } catch (Exception e) {

  e.printStackTrace();

  }

  三、模拟绕过界面的用户认证,而通过selenium使用已保存的cookies信息直接登录界面,下面是通过selenium在浏览器中添加cookies的代码:

  try {

  File cooFile = new File(COOKIE_PATH);

  if(!cooFile.exists()){

  System.out.println("Not found the cookie file in path:" + COOKIE_PATH);

  return;

  }

  BufferedReader bReader = new BufferedReader(new FileReader(cooFile));

  String line;

  while((line = bReader.readLine()) != null){

  String arrCoo[] = line.split("/");

  System.out.println(arrCoo.length);

  String name="",value="",domain="",path="";

  Date expiry = null;

  boolean isSecure = false;

  for (int i = 0; i < arrCoo.length; i++) {

  name = arrCoo[0];

  value = arrCoo[1];

  domain = arrCoo[2];

  path = arrCoo[3];

  expiry = arrCoo[4] != "null"?new Date(arrCoo[4]):null;

  isSecure = Boolean.parseBoolean(arrCoo[5]);

  }

  System.out.println(name +"/"+ value + "/" + domain + "/" + path + "/" + expiry + "/" + isSecure);

  Cookie cookie = new Cookie(name, value, domain, path, expiry, isSecure);

  driver.manage().addCookie(cookie);

  }

  } catch (Exception e) {

  e.printStackTrace();

  }

  以上内容为大家介绍了自动化测试中的Selenium2操作浏览器的Cookies,本文由多测师亲自撰写,希望对大家有所帮助。了解更多自动化测试相关知识:https://www.aichudan.com/xwzx/

联系电话

17727591462

返回顶部