简体   繁体   中英

How to set request cookies using selenium webdriver?

This is my source code

WebDriver driver = new HtmlUnitDriver(true);

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

Cookie cookie = new Cookie("key", "value");
driver.manage().addCookie(cookie);

Set<Cookie> allCookies = driver.manage().getCookies();
for (Cookie loadedCookie : allCookies) {
    System.out.println(String.format("%s -> %s", loadedCookie.getName(), loadedCookie.getValue()));
}

The request header to server doesn't contain the cookie.

If I change the position of the get() method after addCookie(), the getCookies() will return empty.

I try it all day long.

no matter how I google it, i can't find any way to solve my problem

Hope somebody can help me!

I'll appreciate your help!

You are using the wrong reference to get the cookies, you should use

Set<Cookie> allCookies = driver.manage().getCookies();

instead, you are using driver2 reference. where does driver2 refer to?

Update: after your comment

Problem may be with your driver or the version of browser you use! Try doing it with another version of driver or different browser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM