1

我似乎无法弄清楚如何使用 python 为 Selenium 设置带有方括号 [ ] 的 cookie。这就是我正在尝试的:

selenium.create_cookie("test[country]=nl", "path=/, max_age=6000")

结果是:

Traceback (most recent call last):
  File "test.py", line 55, in test
    sel.create_cookie('test[country]=nl', "path=/, max_age=6000")
  File "C:\Python27\lib\site-packages\selenium\selenium.py", line 1813, in create_cookie
    self.do_command("createCookie", [nameValuePair,optionsString,])
  File "C:\Python27\lib\site-packages\selenium\selenium.py", line 225, in do_command
    raise Exception(data)
Exception: ERROR: Invalid parameter.

我怎样才能解决这个问题?

编辑:这是一些代码。它基于 IDE 导出的代码。

from selenium.selenium import selenium
import unittest, time, re
from selenium import webdriver

class country(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*chrome", "http://example.com/")
        self.selenium.start()

    def test_country_cookie_redirect(self):
        sel = self.selenium
        sel.create_cookie('test[country]=nl', "path=/, max_age=6000")
        sel.open("http://example.com")
        self.assertEqual("http://example.com/nl/nld", sel.get_location()) 

    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()
4

1 回答 1

0

使用add_cookie()。例如:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://stackoverflow.com")

browser.add_cookie({"name": "test[country]",
                    "value": "nl",
                    "path": "/",
                    "max_age": 6000})

browser.close()

UPD(使用 webdriver 修改的测试用例):

import unittest
from selenium import webdriver


class country(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.driver = webdriver.Remote("http://127.0.0.1:4444/wd/hub", {'browserName': 'chrome'})

    def test_country_cookie_redirect(self):
        self.driver.add_cookie({"name": "test[country]",
                                "value": "nl",
                                "path": "/",
                                "max_age": 6000})
        self.driver.get("http://example.com")
        self.assertEqual("http://example.com", self.driver.current_url)

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)


if __name__ == "__main__":
    unittest.main()
于 2013-09-29T19:38:05.927 回答