Unable to add a cookie using Selenium & Splinter

2019-02-15 17:55发布

Per below, I'm not sure how to troubleshoot this pretty simple usage scenario.

I have script (that I run about once a month) that functionally does the identical thing and which used to work as of a month ago.

I'd appreciate any pointers on places to start looking into why this does not work.

$ python3
Python 3.6.1 (default, Mar 23 2017, 16:49:06)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from selenium import webdriver
>>> from splinter import Browser
>>> chrome_options = webdriver.ChromeOptions()
>>> browser = Browser('chrome')
>>> browser.cookies.add({'aaa':'bbb'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/dummyuser/.virtualenvs/my-virtualenv/lib/python3.6/site-packages/splinter/driver/webdriver/cookie_manager.py", line 28, in add
    self.driver.add_cookie({'name': key, 'value': value})
  File "/Users/dummyuser/.virtualenvs/my-virtualenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 708, in add_cookie
    self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
  File "/Users/dummyuser/.virtualenvs/my-virtualenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
    self.error_handler.check_response(response)
  File "/Users/dummyuser/.virtualenvs/my-virtualenv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unable to set cookie
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506106 (8a06c39c4582fbfbab6966dbb1c38a9173bfb1a2),platform=Mac OS X 10.13.1 x86_64)

2条回答
贼婆χ
2楼-- · 2019-02-15 18:29

you should open the url first, and load the cookies, then you can open the next url with cookies.you can also open like that if you want open the same url:

driver = webdriver.Chrome(executable_path=r'X:\home\xxx\chromedriver.exe')

cookies = pickle.load(open("cookies.pkl", "rb"))
driver.get("https://www.douban.com/")
for cookie in cookies:
    driver.add_cookie(cookie)
driver.get("https://www.douban.com/")

hope this helps

查看更多
等我变得足够好
3楼-- · 2019-02-15 18:37

The answer of Florent B. works for me as well, just want to put it into the right place.

browser.cookies.add needs to be called after some browser.visit(...)

see Florent's comment:

The method browser.cookies.add is bound to the current domain which is undefined in your example. You need to set the domain first with driver.get('http://...')

查看更多
登录 后发表回答