Can only set Cookies for the current domain

错误信息大致如下:

selenium.common.exceptions.InvalidCookieDomainException: Message: {"errorMessage":"Can only set Cookies for the current domain","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"3390","Content-Type":"application/json;charset=UTF-8",".............中间省略..........,"source":"/cookie","queryKey":{},"chunks":["cookie"]},"urlOriginal":"/session/49cf7b80-e17f-11e7-91f9-7f99614eeee2/cookie"}}
Screenshot: available via screen

有这样几个原因会导致这个错误:

  1. 在add_cookie之前必须先get一次请求
driver.get(url_str)
driver.delete_all_cookies()
driver.add_cookie(cookie)
driver.get(url_str)
  1. cookie的各项key value不对应
{
    "domain": ".dev-tang.com",
    "expirationDate": 2144041822.496113,
    "name": "signin-sso-state-gb",
    "path": "/",
    "value": "7d0ac8d3-7429-4aa5-bd55-405f05fbe03a"
}

注意: domain的值前面有一个点(.)

  1. 在add_cookie之前最好,先调用driver.delete_all_cookies()清除以前的cookie
driver.delete_all_cookies()
  1. 需要注意add_cookie的参数是一个dict,如果你是一个数组/list 记得循环add
for cookie in cookies:
    driver.add_cookie(cookie)
  1. 当排除上面4点,有可能这个才是真正的原因

在你的cookie domain里有get时未曾出现过的域名,所以就无法添加。在selenium里面有这样一段代码:

var currLocation = respond.session.getWindow().location;
    var currDomain = currLocation.host;
    if (currDomain.indexOf(cookie.domain) == -1) {  // Not quite right, but close enough
      throw new WebDriverError(bot.ErrorCode.INVALID_COOKIE_DOMAIN,
          'You may only set cookies for the current domain');
    }

总而言之,认真去看看报出来的错误,总会有收获的。

本博客采用 知识共享署名-禁止演绎 4.0 国际许可协议 进行许可

本文标题:Can only set Cookies for the current domain

本文地址:https://dev-tang.com/post/2017/12/can-only-set-cookies-for-the-current-domain.html

推荐阅读