无法使用Selenium&添加cookie碎片

时间:2017-11-20 13:33:44

标签: python-3.x selenium cookies splinter

如下所示,我不确定如何解决这个非常简单的使用场景。

我有一个脚本(我每个月运行一次)在功能上做同样的事情,并且使用在一个月前工作。

我很感激有关地方的任何指示,以开始研究为什么这不起作用。

$ 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 个答案:

答案 0 :(得分:2)

您应该先打开url并加载cookie,然后才能打开带有cookie的下一个URL。如果要打开相同的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/")

希望这会有所帮助

答案 1 :(得分:0)

Florent B.的答案也适用于我,只是想把它放到正确的位置。

某些browser.cookies.add

之后需要调用

browser.visit(...)

见Florent的评论:

  

方法browser.cookies.add绑定到当前域,在您的示例中未定义。您需要先使用driver.get设置域名(&#39; http://...')