Selenium JS向请求添加cookie

kch*_*hod 4 javascript selenium node.js

我尝试通过JS将Cookie添加到Selenium中的请求中。文档很明显(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);
    });
});
Run Code Online (Sandbox Code Playgroud)

服务器PHP代码:

<?php
    print_r($_COOKIE);
?>
Run Code Online (Sandbox Code Playgroud)

Flo*_* B. 5

由于您在调用addCookie时未定义域,因此未发送cookie。这是发送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();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,它有效。需要使用两次 ``driver.get('http://domain')``,在``addCookie()`` 之前和之后 (2认同)

小智 5

它帮助了我:

driver.manage().addCookie({name: 'notified', value: 'true'});
Run Code Online (Sandbox Code Playgroud)