での Cookie の処理方法 Selenium webdriver

HTTP Cookie は、ユーザーとユーザーの好みに関する情報で構成されます。 キーと値のペアを使用して情報を保存します。 これは、ユーザーが Web サイトを閲覧している間に Web アプリケーションから送信され、Web ブラウザーに保存される小さなデータです。

詳細については、ここをクリックしてください クッキーのテスト.

Selenium Cookie のクエリコマンド

In Selenium Webdriver では、以下の組み込みメソッドを使用して Cookie をクエリし、対話することができます。

Selenium クエリコマンド 出力
driver.manage().getCookies(); すべての Cookie のリストを返す
driver.manage().getCookieNamed(arg0); 名前に従って特定の Cookie を返す
driver.manage().addCookie(arg0); Cookieを作成して追加する
driver.manage().deleteCookie(arg0); 特定のCookieを削除する
driver.manage().deleteCookieNamed(arg0); 名前に従って特定の Cookie を削除します
driver.manage().deleteAllCookies(); すべての Cookie を削除する

Cookie を処理する (受け入れる) 理由 Selenium?

各 Cookie は、名前、値、ドメイン、パス、有効期限、および安全かどうかのステータスに関連付けられています。 クライアントを検証するために、サーバーは Cookie 内のこれらの値をすべて解析します。

   テスト Selenium Web ドライバーを使用する Web アプリケーションでは、Cookie を作成、更新、または削除する必要がある場合があります。

例えば、オンラインショップを自動化する場合ping アプリケーションでは、注文、カートの表示、支払い情報、注文確認などのテストシナリオを自動化する必要がある場合があります。

Cookie が保存されていない場合は、上記のテスト シナリオを実行する前に、毎回ログイン アクションを実行する必要があります。 これにより、コーディングの労力と実行時間が増加します。

解決策は、Cookie をファイルに保存することです。 Later、このファイルから Cookie の値を取得し、現在のブラウザ セッションに追加します。その結果、すべてのログイン手順をスキップできます。 テストケース ドライバーセッションにはこの情報が含まれているためです。

アプリケーションサーバーは、ブラウザセッションを認証済みとして扱い、リクエストされたページに直接アクセスします。 URL.

での Cookie の処理方法 Selenium

我々は使用するだろう https://demo.guru99.com/test/cookie/selenium_aut.php デモの目的のため。

これは 2 ステップのプロセスになります。

ステップ1) アプリケーションにログインし、生成された認証 Cookie を保存します。

Cookie を処理する Selenium

ステップ2) 保存された Cookie を使用して、ユーザー ID とパスワードを使用せずにアプリケーションに再度ログインします。

ステップ1) Cookie情報の保存

package CookieExample;

import java.io.BufferedWriter;		
import java.io.File;		
import java.io.FileWriter;
import java.util.Set;
import org.openqa.selenium.By;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Cookie;		

public class cookieRead{	
        public static void main(String[] args)		
    {
    	WebDriver driver;	
        System.setProperty("webdriver.chrome.driver","G:///chromedriver.exe");					
		driver=new ChromeDriver();        
		driver.get("https://demo.guru99.com/test/cookie/selenium_aut.php");

       				
        // Input Email id and Password If you are already Register		
        driver.findElement(By.name("username")).sendKeys("abc123");							
        driver.findElement(By.name("password")).sendKeys("123xyz");							
        driver.findElement(By.name("submit")).click();					
        		
        // create file named Cookies to store Login Information		
        File file = new File("Cookies.data");							
        try		
        {	  
            // Delete old file if exists
			file.delete();		
            file.createNewFile();			
            FileWriter fileWrite = new FileWriter(file);							
            BufferedWriter Bwrite = new BufferedWriter(fileWrite);							
            // loop for getting the cookie information 		
            	
            // loop for getting the cookie information 		
            for(Cookie ck : driver.manage().getCookies())							
            {			
                Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));																									
                Bwrite.newLine();             
            }			
            Bwrite.close();			
            fileWrite.close();	
            
        }
        catch(Exception ex)					
        {		
            ex.printStackTrace();			
        }		
    }		
}

Code 説明:

  • WebDriver インスタンスの作成
  • driver.get(“https://demo.guru99.com/test/cookie/selenium_aut.php”) を使用してウェブサイトにアクセスします。
  • アプリケーションにログインする
  • を使用して Cookie 情報を読み取ります
    driver.manage().getCookies();
  • ファイルを使用してクッキー情報を保存しますWriter 文字のストリームを書き込むクラスと BufferedWriter テキストをファイルに書き込む、Cookies.data というファイルを作成する
  • 「Cookies.data」ファイルには、「名前、値、ドメイン、パス」とともにすべての Cookie 情報が保存されます。 この情報を取得して、ログイン資格情報を入力せずにアプリケーションにログインできます。
  • 上記のコードを実行すると、以下の画面に示すように、プロジェクト フォルダー構造に Cookie.data ファイルが作成されます。 Cookie.data ファイルを開くと、AUT のログイン認証情報が Cookie 形式で保存されていることがわかります。以下の強調表示された画面を参照してください。

    Cookie を処理する Selenium

ステップ 2) 保存された Cookie を使用してアプリケーションにログインする

ここで、ステップ 1 で生成された Cookie にアクセスし、生成された Cookie を使用してアプリケーションでのセッションを認証します。

package CookieExample;

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.chrome.ChromeDriver;

public class CookieWrite		
{		
  
	public static void main(String[] args){ 
    	WebDriver driver;     
       	System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");					
        driver=new ChromeDriver();					
    try{			
     
        File file = new File("Cookies.data");							
        FileReader fileReader = new FileReader(file);							
        BufferedReader Buffreader = new BufferedReader(fileReader);							
        String strline;			
        while((strline=Buffreader.readLine())!=null){									
        StringTokenizer token = new StringTokenizer(strline,";");									
        while(token.hasMoreTokens()){					
        String name = token.nextToken();					
        String value = token.nextToken();					
        String domain = token.nextToken();					
        String path = token.nextToken();					
        Date expiry = null;					
        		
        String val;			
        if(!(val=token.nextToken()).equals("null"))
		{		
        	expiry = new Date(val);					
        }		
        Boolean isSecure = new Boolean(token.nextToken()).								
        booleanValue();		
        Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);			
        System.out.println(ck);
        driver.manage().addCookie(ck); // This will add the stored cookie to your current session					
        }		
        }		
        }catch(Exception ex){					
        ex.printStackTrace();			
        }		
        driver.get("https://demo.guru99.com/test/cookie/selenium_aut.php");					
}	
	}	

出力: ユーザーIDとパスワードを入力しなくても、ログイン成功画面が直接表示されます。

注: 上記のスクリプトを実行した後にログイン ページが表示された場合は、ハード更新を使用してください。

結論

したがって、テストごとにサーバーにユーザー名とパスワードを何度も入力して検証する必要がなくなります。 Selenium Webdriver を使用すると、時間を大幅に節約できます。