Selenium:尝试使用 cookie 登录 - “只能为当前域设置 cookie" [英] Selenium: Trying to log in with cookies - "Can only set cookies for current domain"

查看:36
本文介绍了Selenium:尝试使用 cookie 登录 - “只能为当前域设置 cookie"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要达到的目标

我正在尝试登录必须使用 Selenium Headless 启用 cookie 的网站,我使用 PhantomJS 作为驱动程序.

问题

我首先使用 Selenium IDE 记录了该过程,使用 Firefox(不是无头)可以正常工作.然后我将代码导出到 Python,现在我无法登录,因为它抛出一个错误,提示只能为当前域设置 Cookie".我不知道为什么我会遇到这个问题,我是不是在正确的域中?

代码

from selenium import webdriverfrom selenium.webdriver.common.by import By从 selenium.webdriver.common.keys 导入密钥从 selenium.webdriver.support.ui 导入选择导入单元测试、时间、重新self.driver = webdriver.PhantomJS()self.driver.implicitly_wait(30)self.base_url = "https://login.example.com"司机 = self.driverdriver.get(self.base_url)all_cookies = self.driver.get_cookies()# 它打印出所有的 cookie 和值就好了用于 all_cookies 中的 cookie打印 cookie['name'] + " --> " + cookies['value']# 给驱动设置cookies对于 all_cookies 中的 s_cookie:c = { s_cookie['name'] : s_cookie['value']}# 这是它抛出错误的地方,说只能为当前域设置 Cookiedriver.add_cookie(c)...

我的尝试

我尝试将 cookie 保存在字典中,转到另一个域,返回到原始域并添加 cookie,然后尝试登录但它仍然不起作用(如 这个线程)

感谢任何帮助.

解决方案

调查每个 cookie 对.我遇到了类似的问题,一些 cookie 属于谷歌.您需要确保 cookie 仅添加到当前域并且也属于同一个域.在这种情况下,您的例外是预料之中的.附带说明一下,如果我没记错的话,你不能使用 localhost 来添加 cookie,如果你这样做的话.更改为 IP 地址.此外,调查您获得的特定域和到期信息的 cookie.看,如果他们返回 null

编辑

我在 Gmail 上做了这个简单的测试来显示你做错了什么.乍一看,我没有注意到您正在尝试获取部分 cookie,一对,并将其添加到域中.由于 cookie 没有任何域、路径、到期等信息,它试图将 cookie 添加到当前域 (127.0.0.1) 并抛出一些不太合理的误导性信息.注意:为了成为有效的 cookie,它必须具有您丢失的正确域和到期信息.

导入单元测试from selenium.webdriver.common.by import By从硒导入网络驱动程序__author__ = '赛弗尔'类 CookieManagerTest(unittest.TestCase):定义设置(自我):self.driver = webdriver.PhantomJS("E:\working\selenium.python\selenium\resources\phantomjs.exe")self.driver.get("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/")self.driver.find_element(By.ID, "Email").send_keys("userid")self.driver.find_element(By.ID, "next").click()self.driver.find_element(By.ID, "Passwd").send_keys("supersimplepassword")self.driver.find_element(By.CSS_SELECTOR, "[type='submit'][value='Sign in']").click()self.driver.maximize_window()定义测试(自我):司机 = self.driverlistcookies = driver.get_cookies()对于 listcookies 中的 s_cookie:#这就是你在做什么c = {s_cookie['name']: s_cookie['value']}print("*****你正在做的部分cookie信息*****
")打印(c)# 需要被完成print("包含域名和到期信息的完整 Cookie
")打印(s_cookie)# driver.add_cookie(s_cookie)定义拆卸(自我):self.driver.quit()

<块引用>

控制台输出:

D:Python34python.exe "D:Program Files (x86)JetBrainsPyCharm Educational Edition 1.0.1helperspycharmutrunner.py" E:workingselenium.pythonseleniumpythonFirstTest.py::CookieManagerTest 真测试于上午 9:59 开始......

*******你正在做的部分cookie信息*******

{'PREF': 'ID=*******:FF=0:LD=en:TM=*******:LM=*******:GM=1:S=*******'}

包含域名和到期信息的完整 Cookie

{'httponly': False, 'name': '*******', 'value': 'ID=*******:FF=0:LD=en:TM=*******:LM=1432393656:GM=1:S=iNakWMI5h_2cqIYi', 'path': '/', 'expires': 'Mon, 22 May 2017 15:07:36 GMT', 'secure':错误,'到期':*******,'域':'.google.com'}

注意:我只是故意用*******替换了一些信息

What I am trying to achieve

I am trying to log in to a website where cookies must be enabled using Selenium headless, I am using PhantomJS for driver.

Problem

I first recorded the procedure using Selenium IDE where it works fine using Firefox (not headless). Then I exported the code to Python and now I can't log in because it's throwing an error saying "Can only set Cookies for the current domain". I don't know why I am getting this problem, am I not on the correct domain?

Code

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import unittest, time, re

        self.driver = webdriver.PhantomJS()
        self.driver.implicitly_wait(30)
        self.base_url = "https://login.example.com"

        driver = self.driver
        driver.get(self.base_url)

        all_cookies = self.driver.get_cookies()

        # It prints out all cookies and values just fine
        for cookie in all_cookies
            print cookie['name'] + " --> " + cookies['value']

        # Set cookies to driver
        for s_cookie in all_cookies:
            c = { s_cookie['name'] : s_cookie['value']}
            # This is where it's throwing an error saying "Can only set Cookies for current domain
            driver.add_cookie(c)

        ...

What I've tried

I've tried saving the cookies in a dict, going to another domain, going back to original domain and added the cookies and then trying to log in but it still doesn't work (as suggested in this thread)

Any help is appreciated.

解决方案

Investigate the each cookies pairs. I ran into the similar issues and some of the cookies belonged to Google. You need to make sure cookies are being added only to the current Domain and also belong to the same Domain. In that case your exception is expected. On a side note, if I recall it correctly you cannot use localhost to add the cookies if you are doing so. Change to IP address. Also, investigate the cookies you are getting specially domain and expiry information. See, if they are returning null

Edit

I did this simple test on Gmail to show what you have done wrong. At first look I did not notice that you are trying to grab partial cookie, a pair, and add that to the domain. Since, the cookie does not have any Domain, path, expiry etc. information it was trying to add the cookie to current domain(127.0.0.1) and throwing some misleading info that did not quite make sense. Notice: in order to be a valid cookie it must have to have the correct Domain and expiry information which you have been missing.

import unittest
from selenium.webdriver.common.by import By

from selenium import webdriver


__author__ = 'Saifur'


class CookieManagerTest(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.PhantomJS("E:\working\selenium.python\selenium\resources\phantomjs.exe")
        self.driver.get("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/")
        self.driver.find_element(By.ID, "Email").send_keys("userid")
        self.driver.find_element(By.ID, "next").click()
        self.driver.find_element(By.ID, "Passwd").send_keys("supersimplepassword")
        self.driver.find_element(By.CSS_SELECTOR, "[type='submit'][value='Sign in']").click()
        self.driver.maximize_window()

    def test(self):
        driver = self.driver
        listcookies = driver.get_cookies()

        for s_cookie in listcookies:
            # this is what you are doing
            c = {s_cookie['name']: s_cookie['value']}
            print("*****The partial cookie info you are doing*****
")
            print(c)
            # Should be done
            print("The Full Cookie including domain and expiry info
")
            print(s_cookie)
            # driver.add_cookie(s_cookie)


    def tearDown(self):
        self.driver.quit()

Console output:

D:Python34python.exe "D:Program Files (x86)JetBrainsPyCharm Educational Edition 1.0.1helperspycharmutrunner.py" E:workingselenium.pythonseleniumpythonFirstTest.py::CookieManagerTest true Testing started at 9:59 AM ...

*******The partial cookie info you are doing*******

{'PREF': 'ID=*******:FF=0:LD=en:TM=*******:LM=*******:GM=1:S=*******'}

The Full Cookie including domain and expiry info

{'httponly': False, 'name': '*******', 'value': 'ID=*******:FF=0:LD=en:TM=*******:LM=1432393656:GM=1:S=iNakWMI5h_2cqIYi', 'path': '/', 'expires': 'Mon, 22 May 2017 15:07:36 GMT', 'secure': False, 'expiry': *******, 'domain': '.google.com'}

Notice: I just replaced some info with ******* on purpose

这篇关于Selenium:尝试使用 cookie 登录 - “只能为当前域设置 cookie"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆