How to set cookies in phantomjs using selenium with python?

enter image description here

Raises the error message "You can only set Cookies for the current domain", but all I did was just put the old cookies. Sometimes I add the "correct" domain, it will cause the error message "Unable to set Cookie". And I tested it in Firefox, Firefox also cannot work.

from selenium import webdriver
driver = webdriver.PhantomJS(executable_path=phantompath)
driver.get('http://stackoverflow.com/')
driver.get_screenshot_as_file('1.png')
cookies = driver.get_cookies()
driver.delete_all_cookies()
driver.get_cookies()
for cookie in cookies:
    driver.add_cookie(cookie)
+4
source share
2 answers

The PhantomJS driver does not support all keys from the cookie dictionary. One way to overcome this problem is to select keys:

from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get('http://stackoverflow.com/')

cookies = driver.get_cookies()

driver.delete_all_cookies()

for cookie in cookies :
    driver.add_cookie({k: cookie[k] for k in ('name', 'value', 'domain', 'path', 'expiry')})
+5
source

cookie. :

driver = webdriver.PhantomJS()
driver.get('http://www.baidu.com')
driver.delete_all_cookies()

for item in cookie_dictionary: 
    driver.add_cookie({
      'domain': '.baidu.com', # note the dot at the beginning
      'name': item['name'],
      'value': item['value'],
      'path': '/',
      'expires': None
    })

driver.get('http://www.baidu.com')
+3

All Articles