Selenium JS添加cookie来请求

时间:2016-03-30 10:07:49

标签: javascript node.js selenium

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

客户端JS代码:

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代码:

<?php
    print_r($_COOKIE);
?>

3 个答案:

答案 0 :(得分:4)

您的Cookie未发送,因为在您调用addCookie时,未定义域。 以下是发送cookie的示例:

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();

答案 1 :(得分:3)

它帮助了我

driver.manage().addCookie({name: 'notified', value: 'true'});

答案 2 :(得分:0)

Cookie作为标头发送。你可以简单地在标题中设置它:

$browser.addHeader('Cookie', "COO=KIE");

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

相关问题