Selenium WebDriver 处理cookie

Selenium WebDriver 处理cookie

 

http://www.cnblogs.com/tobecrazy/p/3985168.html

在使用webdriver测试中,很多地方都使用登陆,cookie能够实现不必再次输入用户名密码进行登陆。

首先了解一下Java Cookie类的一些方法。

在jsp中处理cookie数据的常用方法:
getDomain();返回cookie的域名.
getMaxAge();返回cookie的存活时间
getName();返回cookie的名字
getPath();返回cookie适用的路径
getSecure();如果浏览器通过安全协议发送Cookie将返回true值,如果浏览器使用标准协议刚返回false值
getValue();返回cookie的值
getVersion();返回cookie所遵从的协议版本setComment(String purpose);设置cookie的注释
setPath(String url);设置Cookie的适用路径
setSecure(Boolean flag);设置浏览器是否仅仅使用安全协议来发送cookie,例如使用Https或ssl
setValue(String newvalue);cookie创建后设置一个新的值
setVersion(int v);设置cookie所遵从的协议版本
selenium WebDriver 通过driver.manage().getCookies() 和driver.manage().addCookie(ck); 获取cookie 加载cookie
 
 
首先,获取cookie 保存的browser.data内
复制代码
package com.packt.webdriver.chapter3;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Cookie;

public class Cookies {
    /**
     * @author Young
     * 
     */
    public static void addCookies() {

        WebDriver driver = DriverFactory.getChromeDriver();
        driver.get("http://www.zhihu.com/#signin");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        WebElement user = driver
                .findElement(By.xpath("//input[@name='email']"));
        user.clear();
        user.sendKeys("seleniumcookies@126.com");
        WebElement password = driver.findElement(By
                .xpath("//input[@name='password']"));
        password.clear();
        password.sendKeys("cookies123");

        WebElement submit = driver.findElement(By
                .xpath("//button[@class='sign-button']"));
        submit.submit();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        File file = new File("broswer.data");
        try {
            // delete file if exists
            file.delete();
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            for (Cookie ck : driver.manage().getCookies()) {
                bw.write(ck.getName() + ";" + ck.getValue() + ";"
                        + ck.getDomain() + ";" + ck.getPath() + ";"
                        + ck.getExpiry() + ";" + ck.isSecure());
                bw.newLine();
            }
            bw.flush();
            bw.close();
            fw.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("cookie write to file");
        }
    }
}
复制代码

 

这里,我简单封装了chrome webdriver

复制代码
import java.util.Arrays;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;


public class DriverFactory {

    public static WebDriver create() {
        
        // TODO Auto-generated method stub
        String chromdriver="E:\\chromedriver.exe";
        System.setProperty("webdriver.chrome.driver", chromdriver);
        ChromeOptions options = new ChromeOptions();
     
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability("chrome.switches",
                Arrays.asList("--start-maximized"));
        options.addArguments("--test-type", "--start-maximized");
        WebDriver driver=new ChromeDriver(options);
        return driver;
    }

}
复制代码

接下来 ,读取browser.data,生成cookie  把cookie加载到浏览器

复制代码
package com.packt.webdriver.chapter3;

import java.io.BufferedReader;
 
import java.io.File;
import java.io.FileReader;
 

import java.util.Date;
import java.util.StringTokenizer;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.os.WindowsUtils;

public class UseCookieLogin {

    /**
     * @author Young
     * @param args
     */
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Cookies.addCookies();
        WindowsUtils.tryToKillByName("chrome.exe");
        WindowsUtils.getProgramFilesPath();
        WebDriver driver=DriverFactory.getChromeDriver();
        driver.get("http://www.zhihu.com/");
        try 
        {
            File file=new File("broswer.data");
            FileReader fr=new FileReader(file);
            BufferedReader br=new BufferedReader(fr);
            String line;
            while((line=br.readLine())!= null)
            {
                StringTokenizer str=new StringTokenizer(line,";");
                while(str.hasMoreTokens())
                {
                    String name=str.nextToken();
                    String value=str.nextToken();
                    String domain=str.nextToken();
                    String path=str.nextToken();
                    Date expiry=null;
                    String dt;
                    if(!(dt=str.nextToken()).equals(null))
                    {
                        //expiry=new Date(dt);
                        System.out.println();
                    }
                    boolean isSecure=new Boolean(str.nextToken()).booleanValue();
                    Cookie ck=new Cookie(name,value,domain,path,expiry,isSecure);
                    driver.manage().addCookie(ck);
                }
            }
            
            
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        driver.get("http://www.zhihu.com/");
    }

}
复制代码

 

再次打开之后,就是登陆后的页面

 
转载请注明出处:http://www.cnblogs.com/tobecrazy/ 
posted @ 2016-03-20 01:41  donaldlee  阅读(531)  评论(0编辑  收藏  举报