Selenium Webdriver Processing Cookies

Source: Internet
Author: User
Tags send cookies

In the use of webdriver testing, many places use login, cookies can be implemented without having to enter the user name password to login.

First look at some of the Java cookie class methods.

Common methods for processing cookie data in JSPs: GetDomain () Returns the domain name of the cookie. Getmaxage (); Returns the lifetime of the Cookie GetName (); Returns the name of the cookie GetPath (); Returns the path to which the cookie applies getsecure (); If the browser sends a cookie through the security protocol, it returns a true value If the browser uses a standard protocol that just returns false value GetValue (); Returns the value of the cookie getversion (); Returns the Protocol version setcomment that the cookie complies with (String purpose) , set the comment setpath (String url) of the cookie, set the applicable path of the cookie SetSecure (Boolean flag), set whether the browser only uses the security protocol to send cookies, For example, use HTTPS or Sslsetvalue (String newvalue), set a new value setversion (int v) After the cookie is created, set the protocol version that the cookie complies with selenium Webdriver by Driver.manage (). GetCookies () and Driver.manage (). Addcookie (CK); Get cookie Load cookie First, get cookie saved in Browser.data
ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileWriter;ImportJava.util.concurrent.TimeUnit;Importorg.openqa.selenium.By;ImportOrg.openqa.selenium.WebDriver;Importorg.openqa.selenium.WebElement;ImportOrg.openqa.selenium.Cookie; Public classCookies { Public Static voidMain (string[] args) {Webdriver driver=driverfactory.create (); Driver.get ("Http://selenium.jd-app.com/wp-login.php"); Driver.manage (). Timeouts (). Implicitlywait (10, Timeunit.seconds); Webelement User= Driver.findelement (By.xpath ("//*[@id = ' user_login ']"));        User.clear (); User.sendkeys ("Username"); Webelement Password=driver.findelement (by. XPath ("//*[@id = ' User_pass ']"));        Password.clear (); Password.sendkeys ("Password"); Webelement Submit=driver.findelement (By.xpath ("//*[@id = ' wp-submit ']"));                Submit.submit (); Try{Thread.Sleep (3000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } File File=NewFile ("Broswer.data"); Try        {            //Delete file if existsFile.delete ();            File.createnewfile (); FileWriter FW=NewFileWriter (file); BufferedWriter BW=NewBufferedWriter (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"); }    }}

Here, I simply encapsulated the chrome Webdriver

Importjava.util.Arrays;ImportOrg.openqa.selenium.WebDriver;ImportOrg.openqa.selenium.chrome.ChromeDriver;Importorg.openqa.selenium.chrome.ChromeOptions;Importorg.openqa.selenium.remote.DesiredCapabilities; Public classDriverfactory { Public StaticWebdriver Create () {//TODO auto-generated Method StubString chromdriver= "E:\\chromedriver.exe"; System.setproperty ("Webdriver.chrome.driver", Chromdriver); Chromeoptions Options=Newchromeoptions (); Desiredcapabilities Capabilities=Desiredcapabilities.chrome (); Capabilities.setcapability ("Chrome.switches", Arrays.aslist ("--start-maximized")); Options.addarguments ("--test-type", "--start-maximized"); Webdriver Driver=Newchromedriver (options); returndriver; }}

Next, read the Browser.data, generate a cookie to load the cookie into the browser

ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileReader;Importjava.util.Date;ImportJava.util.StringTokenizer;ImportOrg.openqa.selenium.Cookie;ImportOrg.openqa.selenium.WebDriver; Public classUsecookielogin { Public Static voidMain (string[] args) {//TODO auto-generated Method StubWebdriver driver=driverfactory.create (); Driver.get ("Http://selenium.jd-app.com/wp-admin/"); Try{File File=NewFile ("Broswer.data"); FileReader FR=Newfilereader (file); BufferedReader BR=NewBufferedReader (FR);            String Line;  while((Line=br.readline ())! =NULL) {StringTokenizer str=NewStringTokenizer (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 (); }                    BooleanIssecure=NewBoolean (Str.nexttoken ()). Booleanvalue (); Cookie ck=Newcookies (name,value,domain,path,expiry,issecure);                Driver.manage (). Addcookie (CK); }            }                                }        Catch(Exception e) {e.printstacktrace (); } driver.get ("Http://selenium.jd-app.com/wp-admin/"); }}

Admin page only after login to open, if not logged in will jump landing page, when we load the cookie, see the landing page

Selenium Webdriver Processing Cookies

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.