如何使用 Selenium webdriver 傳送 cookie?
我們可以使用 Selenium webdriver 傳送 cookie。Cookie 儲存在鍵值對中。首先,我們必須新增 cookie,然後才能刪除它們。我們還可以獲取 cookie。
此外,我們必須新增import org.openqa.selenium.Cookie語句以實現 cookie。
語法
Cookie ck = new Cookie("Automation", "QA"); driver.manage().addCookie(ck); driver.manage().getCookies(); driver.manage().deleteAllCookies();
示例
程式碼實現
import java.util.Set; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.Cookie; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class CookiesSend{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); driver.get("https://tutorialspoint.tw/index.htm"); // cookie set with name and value Cookie ck = new Cookie("Automation", "QA"); // cookie newly added driver.manage().addCookie(ck); // get all cookies Set<Cookie> cks = driver.manage().getCookies(); //iterate the cookies for (Cookie cook : ck) { System.out.println("Cookie name is: "+ cook.getName()); System.out.println("Cookie Value is : "+ cook.getValue()); } // delete all driver.manage().deleteAllCookies(); // get cookies Set chs = driver.manage().getCookies(); System.out.println("Cookie count after delete: "+chs.size()); driver.quit(); } }
輸出
廣告