简体   繁体   English

如何使用Selenium WebDriver设置请求Cookie?

[英]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. 服务器的请求标头不包含cookie。

If I change the position of the get() method after addCookie(), the getCookies() will return empty. 如果在addCookie()之后更改get()方法的位置,则getCookies()将返回空。

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 您使用错误的引用来获取Cookie,应该使用

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

instead, you are using driver2 reference. 相反,您正在使用driver2参考。 where does driver2 refer to? driver2在哪里引用?

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 尝试使用其他版本的驱动程序或其他浏览器进行操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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