美文网首页python遨游记我爱编程
phantomJS报错:Can only set Cookies

phantomJS报错:Can only set Cookies

作者: Maql | 来源:发表于2017-03-06 17:07 被阅读1257次

需求

有时候一些场景不得不使用phantomJS来获取页面动态加载的信息,但是遇到一些需要登录状态的页面,绕不过登录,就是能将cookies放入phantomJS中才行了

错误代码

# 获取浏览器
driver = webdriver.PhantomJS(executable_path='phantomjs.exe')
# 拿到cookies信息
cookie = {"SSOLoginState":"1488702265"}
    for key in cookie:
        c = {}
        c['name'] = key
        c['value'] = cookie[key]
        c['domain'] = 'example.com'
        c['page'] = '/'
        c['httponly'] = False
        c['secure'] = False
        driver.add_cookie(c)

报错信息

Can only set Cookies for the current domain...
....
...
Screenshot: available via screen

大概是说不能将cookies放入本域名,可能是跨域了

官网的例子

phantomJS官网
完整的cookies信息应该是这样的:

{ 
  domain: 'example.com',
  expires: 'Sat Oct 11 2014 21:44:33 GMT+0200 (CEST)',
  expiry: 1476128618,
  httponly: false,
  name: 'cookieName',
  path: '/',
  secure: false,
  value: cookieValue
}

原因:

原来cookies中有一个key是path,而不是page!!!!另外还有domain前面 需要加一个. 例如jianshu.com,则正确的domain应该写成

domain: '.jianshu.com'

相关文章

网友评论

  • DAOLANFLER:driver = webdriver.PhantomJS(executable_path=r'D:\ChromeDownload\phantomjs-2.1.1-windows\bin\phantomjs.exe')
    driver.get("http://pythonscraping.com";)
    driver.implicitly_wait(1)
    print(driver.get_cookies())
    savedCookies = driver.get_cookies()

    driver2 = webdriver.PhantomJS(executable_path=r'D:\ChromeDownload\phantomjs-2.1.1-windows\bin\phantomjs.exe')
    driver2.get("http://pythonscraping.com";)
    driver2.implicitly_wait(1)
    driver2.delete_all_cookies()

    for cookie in savedCookies:
    driver2.add_cookie(cookie)

    driver2.get("http://pythonscraping.com";)
    driver.implicitly_wait(2)
    print(driver2.get_cookies())

    把前一个driver 的cookie 传给第二个也会报这个错啊。。。
    DAOLANFLER:换成chromedriver 就行了

本文标题:phantomJS报错:Can only set Cookies

本文链接:https://www.haomeiwen.com/subject/uvsugttx.html