如何使用 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.com/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(); } }
输出
广告