【问题标题】:Selenium JS add cookie to requestSelenium JS 将 cookie 添加到请求中
【发布时间】:2020-01-19 05:59:00
【问题描述】:

我尝试通过 JS 将 cookie 添加到 Selenium 中的请求中。文档很明显(http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_Options.html#addCookie),但我的代码 sn-p 没有将任何 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);
?>

【问题讨论】:

  • console.log 正常工作,它返回“cookie-3”。问题在于显示空数组的 PHP 脚本。

标签: javascript node.js selenium


【解决方案1】:

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

【讨论】:

  • 谢谢,它有效。需要在addCookie()之前和之后使用两次driver.get('http://domain')
【解决方案2】:

它帮助了我:

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

【讨论】:

【解决方案3】:

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

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 2017-09-22
  • 2020-02-22
  • 2018-03-24
  • 2021-02-09
相关资源
最近更新 更多