首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Selenium JS向请求添加cookie

Selenium JS向请求添加cookie
EN

Stack Overflow用户
提问于 2016-03-30 18:07:49
回答 3查看 11.1K关注 0票数 5

我尝试通过JS将cookie添加到Selenium中的请求中。文档很明显(http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_Options.html#addCookie),但是我的代码片段没有向服务器上的PHP脚本传递任何cookie (如下所示)。

客户端JS代码:

代码语言:javascript
复制
var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder()
    .withCapabilities({'browserName': 'firefox'})
    .build();
driver.manage().addCookie("test", "cookie-1");
driver.manage().addCookie("test", "cookie-2").then(function () {
    driver.get('http://localhost/cookie.php').then(function () {
        driver.manage().addCookie("test", "cookie-3");
        driver.manage().getCookie('test').then(function (cookie) {
            console.log(cookie.value);
        });
        setTimeout(function () {
            driver.quit();
        }, 30000);
    });
});

服务器PHP代码:

代码语言:javascript
复制
<?php
    print_r($_COOKIE);
?>
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-03-30 18:52:49

不会发送您的cookie,因为在您调用addCookie时,域尚未定义。下面是发送cookie的示例:

代码语言:javascript
复制
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder()
    .withCapabilities({'browserName': 'firefox'})
    .build();

// set the domain
driver.get('http://127.0.0.1:1337/');

// set a cookie on the current domain
driver.manage().addCookie("test", "cookie-1");

// get a page with the cookie
driver.get('http://127.0.0.1:1337/');

// read the cookie
driver.manage().getCookie('test').then(function (cookie) {
   console.log(cookie);
});

driver.quit();
票数 7
EN

Stack Overflow用户

发布于 2020-01-19 01:19:44

它帮助了我:

代码语言:javascript
复制
driver.manage().addCookie({name: 'notified', value: 'true'});
票数 3
EN

Stack Overflow用户

发布于 2018-03-01 11:21:09

Cookie作为报头发送。您可以简单地在标题中设置它,如下所示:

代码语言:javascript
复制
$browser.addHeader('Cookie', "COO=KIE");

这可以在发送请求之前完成。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36305660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档